<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------


/**
 * 门店公共类
 * @package  htdocs
 * @subpackage  module/base
 * @author   allen.qiang
 * @version 1.0
 */
  
class mallHandler {

	private $dbca;

	function __construct( &$dbca ) {
		$this->dbca = $dbca;
	}

	/**
     * 查询商品咨询信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null|array
     */
	public function searchMall( &$arg_array ) {

	
		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

		//门店ID
		if (isset($arg_array['mallID']) && is_numeric($arg_array['mallID'])) {
			$sql .= ' AND mallID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['mallID'];
		}
		
		//门店编号
		if (isset($arg_array['mallCode']) && !empty($arg_array['mallCode'])) {
			$sql .= ' AND mallCode = ?';
			$params_type .= 's';
			$params_array[] = trim($arg_array['mallCode']);
		}
		
		if(isset($arg_array['mallName']) && !empty($arg_array['mallName'])){
			$sql .= ' AND mallName LIKE ? ';
			$params_type .= 's';
			$params_array[] = '%'.trim($arg_array['mallName']).'%';	
		}

        //市名
        if(isset($arg_array['cityName']) && !empty($arg_array['cityName'])){
            $sql .= ' AND cityName = ? ';
            $params_type .= 's';
            $params_array[] = $arg_array['cityName'];
        }
	
		//门店类型
		
		if(isset($arg_array['mallType']) && is_numeric($arg_array['mallType'])){
			
			$sql .= ' AND mallType = ?';  
			$params_type .= 'i';
			$params_array[] = $arg_array['mallType'];
		}
		
		
		//使用状态
		
		if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
			
			$sql .= ' AND useFlg = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['useFlg'];
		}
		
	
		if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
			$sql .= $arg_array['extend'];
		}

		if ($sql) {
			$sql = 'WHERE ' . substr($sql, 4);
		}

		try {

			if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

				//统计分类数量
				$search_sql = 'SELECT COUNT(*) AS item_count FROM mall_master ' . $sql;
				
				$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				$item_count = $count_array[0]->item_count;
				if ($item_count == 0) {
					$arg_array['count'] = 0;
					return null;
				}

				$arg_array['count'] = $item_count;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

				//分页
				if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				$arg_array['page'] = 1;

				$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

			} else {

				$arg_array['count'] = 0;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

			}

			//查询分类信息
			$search_sql = 'SELECT * FROM mall_master ' . $sql;
			
			
			
			$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
			
			if (!$temp_item_array){
				return null;
			}
			foreach($temp_item_array as &$item) {
				$item_array[] = array(
				'mallID' => $item->mallID,
				'mallName' => $item->mallName,
				'mallCode' => $item->mallCode,
				'mention' => $item->mention,
				'mallType' => $item->mallType,
				'provinceid' => $item->provinceid,
				'provinceName' => $item->provinceName,
				'cityid' => $item->cityid,
				'cityName' => $item->cityName,
				'countyid' => $item->countyid,
				'countyName' => $item->countyName,
				'address' => $item->address,
				'logo' => $item->logo,
				'phone' => $item->phone,
				'mobile' => $item->mobile,
				'breif' => $item->breif,
				'description' =>  $item->description,
				'latitude' => $item->latitude,
				'longitude' => $item->longitude,
				'useFlg'   => $item->useFlg
				);
			}

			return $item_array;

		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}


	/**
	 *查询排序号
	 * 如果没给参数就返回当前排序号最大值+1 
	 */
	public function searchSortOrder(){

		$result = $this->dbca->stmt_query('SELECT MAX(sortOrder) max FROM mall_building');
		return $result[0]->max+1;

	}


	/**
	 * 保存楼宇信息
	 *
	 * @param $_REQUEST
	 * @return arr
	 */
	public function saveBuildingInfo( $arg_array ) {

		//实例公共类
		$commHandler = new commHandler();
		if (!isset($arg_array['buildingName'], $arg_array['floor'], $arg_array['sortOrder'], $arg_array['useFlg'], $arg_array['mallID'], $arg_array['creator'])) {
			return array( 'code' => 400, 'message' => '参数错误' );
		}

		if (empty($arg_array['buildingName'])) {
			return array( 'code' => 400, 'message' => '楼宇不能为空' );
		}

		if (empty($arg_array['floor'])) {
			return array( 'code' => 400, 'message' => '总楼层不能为空' );
		}

		if (!$commHandler->isInteger($arg_array['sortOrder'], 1)) {
			return array( 'code' => 400, 'message' => '排序序号不能为空' );
		}

		if (!in_array($arg_array['useFlg'], array(0, 1))) {
			$arg_array['useFlg'] = 1;
		}

		if (!isset($arg_array['buildingID'])) {
			$arg_array['buildingID'] = null;
		}

		try {

			//查询门店信息
			$m_arg_array = array(
			'mallID' => $arg_array['mallID']
			);
			$mall_array = $this->searchMall( $m_arg_array );
			if (!$mall_array) {
				throw new Exception('门店信息没有找到', 404);
			}

			//新增或修改门店楼宇信息
			$mall_building = new entity('mall_building');
			if (!empty($arg_array['buildingID']) && $arg_array['buildingID'] > 0) {//修改
				$mall_building->buildingID = $arg_array['buildingID'];
				if (!$this->dbca->fetch($mall_building)) {
					throw new Exception('楼宇信息没有找到', 404);
				}
			} else {//增加

				$mall_building->creator = $arg_array['creator'];

			}

			$mall_building->buildingName = $commHandler->convertVar( $arg_array['buildingName'] );
			$mall_building->mallID = $arg_array['mallID'];
			$mall_building->floor = $arg_array['floor'];
			$mall_building->sortOrder = $arg_array['sortOrder'];
			$mall_building->useFlg = $arg_array['useFlg'];
			$this->dbca->save($mall_building);

			return array( 'code' => 200, 'message' => '楼宇保存成功' );

		} catch (Exception $e) {

			if ($e->getCode() > 0) {
				return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
			} else {
				error_log($e->getMessage());
				return array( 'code' => 500, 'message' => '系统错误' );
			}

		}

	}

	/**
	 * 删除楼宇信息
	 * $arg_array = array(
	 * 	
	 * )
	 */	
	public function deleteBuilding($arg_array) {
		$mall_building = new entity('mall_building');

		try{
			$this->dbca->beginTransaction();
			foreach($arg_array as $v){
				$mall_building->buildingID = $v;
				if($this->dbca->fetch($mall_building)){
					$this->dbca->delete($mall_building,'building');
				}
			}
			$this->dbca->commit();
			return array( 'code' => 200, 'message' => '删除成功' );

		}catch(Exception $e){
			$this->dbca->rollBack();
			error_log($e->getMessage());
		}
	}
	/**
     * 修改楼宇使用状态
     * $arg_array = array(
     * 		id => useFlg
     * )
     */
	public function buildingChangeStatus($arg_array) {

		//参数检查
		if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '') {
			return array( 'code' => 400, 'message' => '缺少参数' );
		}


		$str_array = explode('_', $arg_array['useFlg_str']);

		try{
			//检查商品促销是否存在或已经被操作
			$mall_building = new entity('mall_building');
			$mall_building->buildingID = $str_array[0] ;
			if (!$this->dbca->fetch( $mall_building ))
			throw new Exception(sprintf('楼宇号「%d」,的楼宇不存在,请审核后再操作',$str_array[0]) , 400) ;

			//检查商品促销状态是否已经被修改
			if($mall_building->useFlg == $str_array[1] && $str_array[1] == 1)
			throw new Exception(sprintf('楼宇号「%d」,的楼宇已启用',$str_array[0]) , 400) ;

			if($mall_building->useFlg == $str_array[1] && $str_array[1] == 0)
			throw new Exception(sprintf('楼宇号「%d」,的楼宇已禁用',$str_array[0]) , 400) ;

			//保存
			$mall_building->useFlg = $str_array[1] ;
			$this->dbca->save( $mall_building , 'mall_building' );

		}catch (Exception $e) {
			if ($e->getCode() > 0)
			return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
			else {
				error_log($e->getMessage());
				return array( 'code' => 500, 'message' => '系统错误' );
			}
		}

		if($str_array[1] == 1)
		return array( 'code' => 200, 'message' => '楼宇启用成功' );

		else if ($str_array[1] == 0)
		return array( 'code' => 200, 'message' => '楼宇禁用成功' );

	}

	/**
     * 查询楼宇信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null|array
     */
	public function searchBuildingInfo( &$arg_array ) {

		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

		//门店号
		if (isset($arg_array['mallID']) && is_numeric($arg_array['mallID'])) {
			$sql .= ' AND mallID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['mallID'];
		}

		//楼宇ID
		if (isset($arg_array['buildingID']) && is_numeric($arg_array['buildingID'])) {
			$sql .= ' AND buildingID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['buildingID'];
		}

		//楼宇名称
		if (isset($arg_array['buildingName']) && !empty($arg_array['buildingName'])) {
			$sql .= ' AND buildingName = ?';
			$params_type .= 's';
			$params_array[] = $arg_array['buildingName'];
		}

		//使用状态
		if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
			$sql .= ' AND useFlg = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['useFlg'];
		}

		if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
			$sql .= $arg_array['extend'];
		}

		if ($sql) {
			$sql = 'WHERE ' . substr($sql, 4);
		}

		try {

			if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

				//统计分类数量
				$search_sql = 'SELECT COUNT(*) AS item_count FROM mall_building ' . $sql;
				$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				$item_count = $count_array[0]->item_count;
				if ($item_count == 0) {
					$arg_array['count'] = 0;
					return null;
				}

				$arg_array['count'] = $item_count;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

				//分页
				if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				$arg_array['page'] = 1;

				$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

			} else {

				$arg_array['count'] = 0;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

			}

			//查询分类信息
			$search_sql = 'SELECT * FROM mall_building ' . $sql;
			$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

			if (!$temp_item_array)
			return null;

			foreach($temp_item_array as &$item) {
				//$mallID = $item->mallID;
				$mallNameInfo = $this->dbca->stmt_query('SELECT mallName FROM mall_master WHERE mallID = ?','i',$item->mallID);
				$mallName = $mallNameInfo[0]->mallName;

				$item_array[] = array(
				'buildingID' =>$item->buildingID,
				'buildingName'=>$item->buildingName,
				'floor'=>$item->floor,
				'mallName'=>$mallName,
				'useFlg' => $item->useFlg,
				'sortorder' => $item->sortorder,
				'mallID' => $item->mallID
				);
			}
			return $item_array;

		} catch (Exception $e) {
			error_log($e->getMessage());
			return null;

		}

	}

	/**
     *保存分类
     * @param $arg_array
     * @return bool
     */
	public function saveCategory(&$arg_array) {

		if(!isset($arg_array['cateFlg']))
		return array('code' => 400,'message' => '参数错误');

		$cateFlg = $arg_array['cateFlg'];

		if($cateFlg == 1){//1保存大分类 2 保存小分类
			if(!isset($arg_array['form_val']['cateName'],$arg_array['form_val']['sortOrder']))
			return array('code' => 400,'message' => '参数错误');

			if(empty($arg_array['form_val']['cateName']))
			return array('code' => 400,'message' => '一级分类名称为空');
		}elseif($cateFlg == 2){
			if(!isset($arg_array['form_val']['cateName'],$arg_array['form_val']['cmiddName'],$arg_array['form_val']['sortOrder']))
			return array('code' => 400,'message' => '参数错误');
			if(empty($arg_array['form_val']['cateName']))
			return array('code' => 400,'message' => '未选择一级分类');
			if(empty($arg_array['form_val']['cmiddName']))
			return array('code' => 400,'message' => '二级分类名称不能为空');
		}

		if(empty($arg_array['form_val']['sortOrder']) || $arg_array['form_val']['sortOrder']<0 )
		return array('code' => 400,'message' => '分类排序不正确');


		$categoryID = isset($arg_array['categoryID']) ? trim($arg_array['categoryID']) : '';
		$CategoryName = $arg_array['form_val']['cateName'];
		$middName = isset($arg_array['form_val']['cmiddName'])?$arg_array['form_val']['cmiddName']:'';
		$useFlg = $arg_array['form_val']['useflg'];
		$sortorder = $arg_array['form_val']['sortOrder'];

		$cid_arr = explode('_',$categoryID);

		try{
			//1保存大分类 2 保存小分类
			if($cateFlg == 1){
				$b_category = new entity('mall_bigCategory');
				$b_category->bigCategoryID = $cid_arr[0];
				if($this->dbca->fetch($b_category)){
					$b_category->bigCategoryName = $CategoryName;
					$b_category->useFlg = $useFlg;
					$b_category->creator = $arg_array['creator'];
					$b_category->sortorder = $sortorder;
					$this->dbca->save($b_category,'mall');
				}else{
					$b_category->bigCategoryName = $CategoryName;
					$b_category->useFlg = $useFlg;
					$b_category->creator = $arg_array['creator'];
					$b_category->sortorder = $sortorder;
					$this->dbca->save($b_category,'mall');
				}
			}elseif($cateFlg == 2){
				$m_category = new entity('mall_midCategory');
				$m_category->midCategoryID = $cid_arr[1];
				if($this->dbca->fetch($m_category)){
					$m_category->bigCategoryID = $CategoryName;
					$m_category->midCategoryName = $middName;
					$m_category->useFlg = $useFlg;
					$m_category->creator = $arg_array['creator'];
					$m_category->sortorder = $sortorder;
					$this->dbca->save($m_category,'mall');

					//如果是门店 更新映射表
					if($arg_array['currentMallID'] ){
						$category_map = new entity('mall_category_map');
						$category_map->creator = $arg_array['creator'];
						$category_map->mallID = $arg_array['currentMallID'];
						$category_map->bigCategoryID = $CategoryName;
						$category_map->midCategoryID = $cid_arr[1];
						$this->dbca->save($category_map,'mall');
					}
				}else{
					$m_category->bigCategoryID = $CategoryName;
					$m_category->midCategoryName = $middName;
					$m_category->useFlg = $useFlg;
					$m_category->creator = $arg_array['creator'];
					$m_category->sortorder = $sortorder;
					$this->dbca->save($m_category,'mall');

					$midCategoryID = $this->dbca->insert_id;
					//如果是门店 插入映射表中
					if($arg_array['currentMallID'] ){
						$category_map = new entity('mall_category_map');
						$category_map->creator = $arg_array['creator'];
						$category_map->mallID = $arg_array['currentMallID'];
						$category_map->bigCategoryID = $CategoryName;
						$category_map->midCategoryID = $midCategoryID;
						$this->dbca->save($category_map,'mall');
					}
				}
			}
			return array('code'=>200,'message'=>'保存成功');
		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}
	}

	/**
     * 获取大分类
     * @return mixed
     */
	public function getBigCate() {
		$bigcate = $this->dbca->stmt_query('SELECT * FROM mall_bigCategory');
		return  $bigcate;
	}

	/**
     * 获取分类信息
     * @param $categoryID
     * @return mixed
     */
	public function getCateInfo($categoryID) {

		$cate_arr = explode('_',$categoryID);

		switch(count($cate_arr)){
			//大分类
			case 1:
				$cate = $this->dbca->stmt_query('SELECT  * FROM mall_bigCategory WHERE bigCategoryID = ?','i',$cate_arr[0]);
				break;
				//中分类
			case 2:
				$cate = $this->dbca->stmt_query('SELECT  * FROM mall_midCategory WHERE midCategoryID = ?','i',$cate_arr[1]);
				break;
		}

		return $cate;
	}

	/**
     * 门店获取一级分类信息
     * @param $arg_array
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     *      'bigCategoryName' => string 一级分类名
     *      'bigCategoryID' => string 一级分类ID
     * )
     * @return array
     */
	public function searchBigCategory( &$arg_array ) {

		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

		//分类名称查询
		if(isset($arg_array['bigCategoryName']) && !empty($arg_array['bigCategoryName'])){
			$sql .= ' AND  bigCategoryName = ?';
			$params_type .= 's';
			$params_array[] = $arg_array['bigCategoryName'];
		}

		//分类号查询
		if(isset($arg_array['bigCategoryID']) && is_numeric($arg_array['bigCategoryID']) ){
			$sql .= ' AND  bigCategoryID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['bigCategoryID'];
		}

		//使用状态
		if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
			$sql .= ' AND useFlg = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['useFlg'];
		}

		if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
			$sql .= $arg_array['extend'];
		}


		if ($sql) {
			$sql = ' WHERE ' . substr($sql, 4);
		}

		try {

			if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

				//统计分类数量
				$search_sql = 'SELECT COUNT(*) AS item_count FROM mall_bigCategory ' . $sql;
				$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				$item_count = $count_array[0]->item_count;
				if ($item_count == 0) {
					$arg_array['count'] = 0;
					return null;
				}

				$arg_array['count'] = $item_count;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

				//分页
				if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				$arg_array['page'] = 1;

				$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

			} else {

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

			}

			//查询分类信息
			$search_sql = 'SELECT * FROM mall_bigCategory ' . $sql;
			$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
			if (!$temp_item_array) {
				return null;
			}

			foreach($temp_item_array as $val){
				$item_array[] = array(
				'bigCategoryID' => $val->bigCategoryID,
				'bigCategoryName' => $val->bigCategoryName,
				'useFlg' => $val->useFlg,
				'sortorder' => $val->sortorder
				);
			}

			return $item_array;

		} catch (Exception $e) {

			error_log($e->getMessage());
			return array( 'code' => 500, 'message' => '系统错误' );

		}

	}

	/**
     * 门店获取二级分类信息
     * @param $arg_array
     * * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     *      'midCategoryName' => string 二级分类名
     *      'midCategoryID' => string 二级分类ID
     *      'bigCategoryID' => string 一级分类ID 必须
     * )
     * @return array
     */
	public function searchMidCategory( &$arg_array ) {

		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

		//查询一级下的二级分类
		if(isset($arg_array['bigCategoryID']) && is_numeric($arg_array['bigCategoryID'])){
			$sql .= ' AND  bigCategoryID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['bigCategoryID'];
		}

		//二级分类名查询
		if(isset($arg_array['midCategoryName']) && !empty($arg_array['midCategoryName'])){
			$sql .= ' AND  midCategoryName = ?';
			$params_type .= 's';
			$params_array[] = $arg_array['midCategoryName'];
		}

		//二级分类号查询
		if(isset($arg_array['midCategoryID']) && is_numeric($arg_array['midCategoryID'])){
			$sql .= ' AND  midCategoryID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['midCategoryID'];
		}

		//使用状态
		if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
			$sql .= ' AND useFlg = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['useFlg'];
		}

		if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
			$sql .= $arg_array['extend'];
		}

		if ($sql) {
			$sql = ' WHERE ' . substr($sql, 4);
		}

		try {

			if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

				//统计分类数量
				$search_sql = 'SELECT COUNT(*) AS item_count FROM mall_midCategory ' . $sql;
				$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				$item_count = $count_array[0]->item_count;
				if ($item_count == 0) {
					$arg_array['count'] = 0;
					return null;
				}

				$arg_array['count'] = $item_count;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

				//分页
				if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				$arg_array['page'] = 1;

				$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

			} else {

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

			}

			//查询分类信息
			$search_sql = 'SELECT * FROM mall_midCategory ' . $sql;
			$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
			if (!$temp_item_array) {
				return null;
			}

			$big_category_array = array();

			foreach($temp_item_array as $val) {

				if (!isset($big_category_array[$val->bigCategoryID])) {
					$big_arg_array = array(
					'bigCategoryID' => $val->bigCategoryID
					);
					$tem_big_category_array = $this->searchBigCategory( $big_arg_array );
					if (!$tem_big_category_array) {
						continue;
					}
					$big_category_array[$val->bigCategoryID] = $tem_big_category_array[0];
				}

				$item_array[] = array(
				'midCategoryID' => $val->midCategoryID,
				'midCategoryName' => $val->midCategoryName,
				'bigCategoryID' => $val->bigCategoryID,
				'useFlg' => $val->useFlg,
				'sortorder' => $val->sortorder,
				'bigCategoryName' => $big_category_array[$val->bigCategoryID]['bigCategoryName']
				);
			}

			return $item_array;

		} catch (Exception $e) {

			error_log($e->getMessage());
			return array( 'code' => 500, 'message' => '系统错误' );

		}

	}


	/**
     * 删除分类
     * @param $arg_array
     * $arg_array = Array(
        [delete_str] => 一级分类ID_二级分类ID
     * )
     * @return array
     */
	public function deleteCate ( $arg_array ) {

		//将字符串截成数组
		$delete_array = explode('_', $arg_array['delete_str']);

		try {
			//对每个数组元素进行大、中、小分类判断
			foreach( $delete_array as &$b_l ) {
				$cateArr = explode('-', $b_l);
				switch (count($cateArr)){
					case 1:
						//删除分一级类，需要删除对应的中分类和小分类
						$this->dbca->stmt_query('DELETE FROM mall_bigCategory WHERE bigCategoryID = ?', 'i', $cateArr[0]);
						
						break;
					case 2:
						//删除二级分类，需要删除中分类对应的小分类
						$this->dbca->stmt_query('DELETE FROM mall_midCategory WHERE bigCategoryID = ? AND midCategoryID = ?','ii', array($cateArr[0], $cateArr[1]));
						break;
				}
			}

			return array( 'code' => 200, 'message' => '分类删除成功' );

		} catch (Exception $e) {
			error_log($e->getMessage());
			return array( 'code' => 500, 'message' => '系统错误' );
		}
	}

	/**
     * 分类的使用和禁用
     * @param unknown_type $arg_array
     * $arg_array = Array(
        [useFlg_str] => 一级分类ID_二级分类ID_使用标志
     * )
     * @return array
     */
	public function actionCategory ( $arg_array ) {
		//检查参数
		if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '')
		return array('code' => 400, 'message' => '缺少参数' );

		$str_array = explode('_', $arg_array['useFlg_str']);
		try{
			switch (count($str_array)){
				case 2:	//大分类
				$bigCate = new entity('mall_bigCategory');
				$bigCate->bigCategoryID = $str_array[0];
				if(!$this->dbca->fetch($bigCate))
				return array('code' => 400, 'message' => sprintf('大分类「%s」信息不存在',$str_array[0]));

				$bigCate->useFlg = $str_array[1];
				$this->dbca->save($bigCate, 'mall');
				return array('code' => 200, 'message' => '分类使用状态更新成功');
				break;
				case 3:	//中分类
				$midCate = new entity('mall_midCategory');
				$midCate->bigCategoryID = $str_array[0];
				$midCate->midCategoryID = $str_array[1];
				if(!$this->dbca->fetch($midCate))
				return array('code' => 400, 'message' => sprintf('中分类「%s」信息不存在',$str_array[1]));

				$midCate->useFlg = $str_array[2];
				$this->dbca->save($midCate, 'mall');
				return array('code' => 200, 'message' => '分类使用状态更新成功');
				break;

			}
		}catch(Exception $e) {

			error_log($e->getMessage());
			return array( 'code' => 500, 'message' => '系统错误' );

		}
	}

	/**
     * 门店对分类的启用和禁用
     * @param unknown_type$arg_array
     * $arg_array = array (
     *       'useFlg'=>使用标志，
     *       'cateID'=>一级二级分类ID字符串,
     *       'currentMall'=>门店ID
     * )
     * * @return array
     */
	public function actionUse($arg_array) {
		global $G_PGLOB;
		$useFlg = $arg_array['useFlg'];//使用标志
		$cateID_arr = explode('_',$arg_array['cateID']);
		$bigcateID = $cateID_arr[0];//一级分类ID
		$midcateID = $cateID_arr[1];//二级分类ID
		$currentMall = $arg_array['currentMall'];//门店ID
		if($useFlg == 0 ){

			$this->dbca->stmt_query('delete from mall_category_map where mallID = ? and bigCategoryID =? and midCategoryID = ?','iii',array($currentMall,$bigcateID,$midcateID));
			return array('code'=>200,'message'=>'禁用成功');

		}elseif($useFlg == 1){
			$malluse = new entity('mall_category_map');
			$malluse->mallID = $currentMall;
			$malluse->bigCategoryID = $bigcateID;
			$malluse->midCategoryID = $midcateID;
			if($this->dbca->fetch($malluse)){
				return array('code'=>400,'message'=>'该分类已启用');
			}else{
				$malluse->creator = $G_PGLOB->currentUserID;
				$this->dbca->save($malluse);
				return array('code'=>200,'message'=>'启用成功');
			}
		}

	}

	/**
     * 获取所有分类
     * @param $currentMall
     * @return array
     */
	public function searchAllCate ($currentMall) {

		global $G_PGLOB;

		$search_bigcate = $this->dbca->stmt_query('select * from mall_bigCategory');

		$cate_arr = array();

		foreach($search_bigcate as $val){

			$search_midcate = $this->dbca->stmt_query('select mcm.mallID, mm.bigCategoryID,mm.midCategoryName,mm.midCategoryID,mm.sortorder from mall_midCategory mm left join mall_category_map mcm on (mm.midCategoryID = mcm.midCategoryID and mcm.mallID = ?) where mm.bigCategoryID = ?','ii',array($currentMall,$val->bigCategoryID));

			$midcate_arr = array();
			if($search_midcate){

				foreach($search_midcate as $mval){

					$useFlg = 0;
					if($mval->mallID == $G_PGLOB->currentMallID){
						$useFlg = 1;
					}

					$midcate_arr[$mval->midCategoryID] = array(
					'midCategoryID' => $mval->midCategoryID,
					'midCategoryName' => $mval->midCategoryName,
					'bigCategoryID' => $mval->bigCategoryID,
					'useFlg' => $useFlg,
					'sortorder' => $mval->sortorder
					);
				}
			}

			$cate_arr[$val->bigCategoryID] = array(
			'bigCategoryID' => $val->bigCategoryID,
			'bigCategoryName' => $val->bigCategoryName,
			'sortorder' => $val->sortorder,
			'midcate' => $midcate_arr
			);

		}
		return $cate_arr;
	}

	/**
     * 获取预约信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * 
     *       'merchantID'=> int 商户ID
     * 		 'reserveID' => int 预约ID
     * 		 'useFlg' => int 使用标识
     * 		 'current_date' => string 当前日期
     * 		 'current_time' => int 当前时间，只传时，0到23之间
     * )
     * @return null|array
     */
	public function searchReserveInfo(&$arg_array){
		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

		//预约ID
		if (isset($arg_array['reserveID']) && is_numeric($arg_array['reserveID'])) {
			$sql .= ' AND reserve.reserveID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['reserveID'];
		}

		//商户ID
		if (isset($arg_array['merchantID']) && is_numeric($arg_array['merchantID'])) {
			$sql .= ' AND reserve.merchantID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['merchantID'];
		}

		//预约使用状态
		if (isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
			$sql .= ' AND reserve.useFlg = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['useFlg'];
		}

        //商户使用状态
        if (isset($arg_array['merchant_useFlg']) && is_numeric($arg_array['merchant_useFlg']) && in_array($arg_array['merchant_useFlg'], array(0, 1))) {
            $sql .= ' AND merchant.useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['merchant_useFlg'];
        }

		//日期
		if (isset($arg_array['current_date']) && $arg_array['current_date'] != '') {
			$sql .= ' AND reserve.startDate <= ? AND reserve.endDate >= ?';
			$params_type .= 'ss';
			$params_array[] = $arg_array['current_date'];
			$params_array[] = $arg_array['current_date'];
		}

		//时间
		if (isset($arg_array['current_time']) && ($arg_array['current_time'] >=0 && $arg_array['current_time'] <=23)) {
			$sql .= ' AND reserve.startTime <= ? AND reserve.endTime >= ?';
			$params_type .= 'ss';
			$params_array[] = $arg_array['current_time'];
			$params_array[] = $arg_array['current_time'];
		}

		if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
			$sql .= $arg_array['extend'];
		}

		if ($sql) {
			$sql = 'WHERE ' . substr($sql, 4);
		}

		try {

			if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

				//统计分类数量
				$search_sql = 'SELECT COUNT(*) AS item_count FROM mall_merchant_reserve reserve 
								INNER JOIN mall_merchant_master merchant ON reserve.merchantID=merchant.merchantID ' . $sql;

				$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				$item_count = $count_array[0]->item_count;

				if ($item_count == 0) {
					$arg_array['count'] = 0;
					return null;
				}

				$arg_array['count'] = $item_count;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', 'reserve.'.$arg_array['sortname'], $arg_array['sortorder']);

				//分页
				if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				$arg_array['page'] = 1;

				$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

			} else {

				$arg_array['count'] = 0;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', 'reserve.'.$arg_array['sortname'], $arg_array['sortorder']);

			}

			//查询信息
			$search_sql = 'SELECT reserve.* FROM mall_merchant_reserve reserve 
							INNER JOIN mall_merchant_master merchant ON reserve.merchantID=merchant.merchantID ' . $sql;
			$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
			if (!$temp_item_array)
			return null;

			foreach($temp_item_array as &$item) {
				$item_array[] = array(
				'merchantID' => $item->merchantID,
				'reserveID' => $item->reserveID,
				'title' => $item->title,
				'startDate' => $item->startDate,
				'endDate' => $item->endDate,
				'startTime' => $item->startTime,
				'endTime' => $item->endTime,
				'description' => $item->description,
				'useFlg' => $item->useFlg,
				);
			}

			return $item_array;

		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}
	}



	/**
     *	保存预约信息
     * @param array $arg_array	保存参数
     * 			int	$arg_array['reserveID']		必选
     * 			int	$arg_array['merchantID']	必选
     * 			int	$arg_array['contactor']		必选
     * 			int	$arg_array['mobile']		可选
     * 			int	$arg_array['phone']			可选
     * 			int	$arg_array['reserve_date']	必选
     * 			int	$arg_array['reserve_time']	必选
     * 			int	$arg_array['reserve_number']必选
     * 			int	$arg_array['remark']		必选
     */
	public function saveCustReserveInfo($arg_array){
		//校验商户是否存在
		$merchant_obj = new entity('mall_merchant_master');
		$merchant_obj->merchantID = $arg_array['merchantID'];
		if (!$this->dbca->fetch($merchant_obj)) {
			die(json_encode(array('code'=>400,'message'=>'商户信息不存在')));
		}
		if ($merchant_obj->useFlg != 1) {
			die(json_encode(array('code'=>400,'message'=>'商户信息已失效')));
		}

		//检测商户预约信息是否存在
		$merchant_reserve_obj = new entity('mall_merchant_reserve');
		$merchant_reserve_obj->reserveID = $arg_array['reserveID'];
		$merchant_reserve_obj->merchantID = $arg_array['merchantID'];
		if (!$this->dbca->fetch($merchant_reserve_obj)) {
			die(json_encode(array('code'=>400,'message'=>'商户预约信息不存在')));
		}
		if ($merchant_reserve_obj->useFlg != 1) {
			die(json_encode(array('code'=>400,'message'=>'商户预约信息已失效')));
		}

		$current_hour = date('H');
		$current_date = date(G_DEFAULT_DATE_FORMAT);
		//检测预约是否过期
		if ($current_date < $merchant_reserve_obj->startDate) {
			return array('code'=>400,'message'=>'预约活动尚未开始');
		}
		if ($current_date > $merchant_reserve_obj->endDate) {
			return array('code'=>400,'message'=>'预约活动已结束');
		}
		if ($arg_array['reserve_date'] == $current_date && $arg_array['reserve_time'] < $current_hour) {
			return array('code'=>400,'message'=>'预约时间已过，请重新选择<br>当前时间：'. $current_hour .':00<br>您选择的时间'.$arg_array['reserve_time']);
		}

		if ($arg_array['reserve_date'] < $current_date) {
			return array('code'=>400,'message'=>'预约日期不能小于当前日期');
		}
		if ($arg_array['reserve_date'] < $merchant_reserve_obj->startDate || $arg_array['reserve_date'] > $merchant_reserve_obj->endDate) {
			return array('code'=>400,'message'=>'预约日期不能超出允许的预约日期<br>允许预约日期：'.$merchant_reserve_obj->startDate.'至'.$merchant_reserve_obj->endDate.',选择的日期：'.$arg_array['reserve_date']);
		}
		if ($arg_array['reserve_time'] < $merchant_reserve_obj->startTime || $arg_array['reserve_time'] > $merchant_reserve_obj->endTime) {
			return array('code'=>400,'message'=>'预约时间不能超出允许的预约时间<br>允许预约时间段：'.$merchant_reserve_obj->startTime.'至'.$merchant_reserve_obj->endTime.',选择的日期：'.$arg_array['reserve_time']);
		}

		$commHandler = new commHandler($this->dbca);
		if (isset($arg_array['phone'])) {
			$arg_array['phone'] = $commHandler->convertVar($arg_array['phone']);
		}else{
			$arg_array['phone'] = '';
		}

		$merchant_reserve_cust_detail = new entity('mall_merchant_reserve_user_detail');
		$merchant_reserve_cust_detail->creator = 'system';
		$merchant_reserve_cust_detail->createTime = date(G_DEFAULT_DATETIME_FORMAT);
		$merchant_reserve_cust_detail->reserveID = $arg_array['reserveID'];
		$merchant_reserve_cust_detail->contactor = $arg_array['contactor'];
		$merchant_reserve_cust_detail->mobile	 = $arg_array['mobile'];
		$merchant_reserve_cust_detail->phone	 = $arg_array['phone'];
		$merchant_reserve_cust_detail->reserved_date	 = $arg_array['reserve_date'];
		$merchant_reserve_cust_detail->reserved_time	 = $arg_array['reserve_time'];
		$merchant_reserve_cust_detail->reserve_number	 = $arg_array['reserve_number'];
		$merchant_reserve_cust_detail->reserve_status	 = 0;
		$merchant_reserve_cust_detail->message			 = isset($arg_array['remark']) ? $arg_array['remark'] : '';
		$merchant_reserve_cust_detail->pcustID			 = isset($arg_array['userID']) ? $arg_array['userID'] : 0;
		try {
			$this->dbca->save($merchant_reserve_cust_detail,'mall');
			return array('code'=>200,'message'=>'预约成功');
		}catch (Exception $e){
			error_log($e->getMessage());
			return array('code'=>400,'message'=>'预约失败');
		}

	}

	/**
     * 查询用户信息
     * @param $arg_array
     * @return array|null
     */
	public function searchUserList( &$arg_array ) {

		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

        //所属门店的ID
        if (isset($arg_array['mallID']) && !empty($arg_array['mallID'])) {
            $sql .= ' AND mmm.mallID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['mallID'];
        }

		//用户号
		if (isset($arg_array['userID']) && !empty($arg_array['userID'])) {
			$sql .= ' AND mmu.userID = ?';
			$params_type .= 's';
			$params_array[] = $arg_array['userID'];
		}

		//用户姓名
		if (isset($arg_array['trueName']) && !empty($arg_array['trueName'])) {
			$sql .= ' AND mmu.trueName = ?';
			$params_type .= 's';
			$params_array[] = '%' . $arg_array['trueName'] . '%';
		}

		//商户ID
		if (isset($arg_array['merchantID']) && is_numeric($arg_array['merchantID'])) {
			$sql .= ' AND mmu.merchantID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['merchantID'];
		}

		//商户名
		if (isset($arg_array['merchantName']) && !empty($arg_array['merchantName'])) {
			$sql .= ' AND mmu.merchantName like ? ';
			$params_type .= 's';
			$params_array[] = '%'.$arg_array['merchantName'].'%';
		}

		//使用状态
		if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
			$sql .= ' AND mmu.useFlg = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['useFlg'];
		}

		if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
			$sql .= $arg_array['extend'];
		}

		if ($sql) {
			$sql = 'WHERE ' . substr($sql, 4);
		}

		try {

			if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

				//统计分类数量
				$search_sql = 'SELECT COUNT(*) AS item_count FROM mall_merchant_user mmu LEFT JOIN mall_merchant_master mmm ON mmu.merchantID = mmm.merchantID ' . $sql;
				$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				$item_count = $count_array[0]->item_count;
				if ($item_count == 0) {
					$arg_array['count'] = 0;
					return null;
				}

				$arg_array['count'] = $item_count;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

				//分页
				if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				$arg_array['page'] = 1;

				$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

			} else {

				$arg_array['count'] = 0;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

			}

			//查询信息
			$search_sql = 'SELECT mmu.merchantID,mmu.merchantName,mmu.userID,mmu.trueName,mmu.userPwd,mmu.email,mmu.mobile,mmu.phone,mmu.useFlg,mmm.mallID FROM mall_merchant_user mmu
			             LEFT JOIN mall_merchant_master mmm ON mmu.merchantID = mmm.merchantID '
                          . $sql;

			$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

			if (!$temp_item_array)
			return null;

			foreach($temp_item_array as &$item) {
				$item_array[] = array(
				'merchantID' => $item->merchantID,
				'merchantName' => $item->merchantName,
				'userID' => $item->userID,
				'trueName' => $item->trueName,
				'userPwd' => $item->userPwd,
				'email' => $item->email,
				'mobile' => $item->mobile,
				'phone' => $item->phone,
				'useFlg' => $item->useFlg,
                'mallID' => $item->mallID
				);
			}
			return $item_array;

		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}

	/**
     * 保存用户
     * @param $table
     * @param $arg_array
     * $arg_array = Array(
        'edaction' => edit|save   必选
        'merchantID' => 商户ID    必选
        'userID' => 用户ID        必选
        'trueName' => 用户名      必选
        'userPwd' => 密码         必选
        'repeatPwd' => 密码       必选
        'mobile' => 手机
        'phone' => 电话
        'email' => email
        'useFlg' => 使用标志
    )
     * @return array
     */
	public function saveUser($arg_array) {

		//获取商户名
		$merchantName = $this->dbca->stmt_query('select merchantName from mall_merchant_master where merchantID=?','i',$arg_array['merchantID']);

		$arg_array['merchantName'] = $merchantName[0]->merchantName;

		//实例化公共类
		$commHandler = new commHandler();

		if (!isset($arg_array['merchantID'],$arg_array['userID'], $arg_array['trueName'], $arg_array['userPwd'],$arg_array['mobile'])) {
			return array( 'code' => 400, 'message' => '参数错误' );
		}

		if (empty($arg_array['userID'])) {
			return array( 'code' => 400, 'message' => '用户名不能为空' );
		}

		if (empty($arg_array['trueName'])) {
			return array( 'code' => 400, 'message' => '用户姓名不能为空' );
		}

		if (!$commHandler->isPwd($arg_array['userPwd'])) {
			return array( 'code' => 400, 'message' => '密码必须是6-30位字符，可使用字母、数字或符号的组合' );
		}
		if ($arg_array['userPwd'] != $arg_array['repeatPwd']) {
			return array( 'code' => 400, 'message' => '两次输入的密码不一致' );
		}

		try {

			$savetable = new entity('mall_merchant_user');
			$savetable->userID = $arg_array['userID'];
			if($this->dbca->fetch($savetable))
			return array('code'=>400,'message'=>'用户名已存在');

			$savetable->creator = $arg_array['creator'];
			$savetable->merchantID = $arg_array['merchantID'];
			$savetable->userID = $arg_array['userID'];
			$savetable->trueName = $arg_array['trueName'];
			$savetable->userPwd = md5($arg_array['userPwd']);
			$savetable->mobile = $arg_array['mobile'];
			$savetable->phone = $arg_array['phone'];
			$savetable->email = $arg_array['email'];
			$savetable->useFlg = $arg_array['useFlg'];
			$savetable->merchantName = $arg_array['merchantName'];

			$this->dbca->save($savetable);
			return array( 'code' => 200, 'message' => '保存成功' );

		}catch (Exception $e) {

			error_log($e->getMessage());
			return array( 'code' => 500, 'message' => '系统错误' );

		}
	}

	/**
     * 编辑用户
     * @param $table
     * @param $arg_array
     * $arg_array = Array(
        'edaction' => edit|save   必选
        'merchantID' => 商户ID    必选
        'userID' => 用户ID        必选
        'trueName' => 用户名      必选
        'userPwd' => 密码
        'repeatPwd' => 密码
        'mobile' => 手机
        'phone' => 电话
        'email' => email
        'useFlg' => 使用标志
    )
     * @return array
     */
	public function editUser($arg_array) {

		//获取商户名
		$merchantName = $this->dbca->stmt_query('select merchantName from mall_merchant_master where merchantID=?','i',$arg_array['merchantID']);

		$arg_array['merchantName'] = $merchantName[0]->merchantName;

		//实例化公共类
		$commHandler = new commHandler();

		if (!isset($arg_array['merchantID'],$arg_array['userID'], $arg_array['trueName'], $arg_array['userPwd'],$arg_array['mobile'])) {
			return array( 'code' => 400, 'message' => '参数错误' );
		}

		if (empty($arg_array['userID'])) {
			return array( 'code' => 400, 'message' => '用户名不能为空' );
		}

		if (empty($arg_array['trueName'])) {
			return array( 'code' => 400, 'message' => '用户姓名不能为空' );
		}

		if (!empty($arg_array['userPwd'])) {
			if (!$commHandler->isPwd($arg_array['userPwd'])) {
				return array( 'code' => 400, 'message' => '密码必须是6-30位字符，可使用字母、数字或符号的组合' );
			}
			if ($arg_array['userPwd'] != $arg_array['repeatPwd']) {
				return array( 'code' => 400, 'message' => '两次输入的密码不一致' );
			}
		}
		try {
			$savetable = new entity('mall_merchant_user');
			$savetable->userID = $arg_array['userID'];
			if($this->dbca->fetch($savetable)){

				$savetable->creator = $arg_array['creator'];
				$savetable->merchantID = $arg_array['merchantID'];
				$savetable->userID = $arg_array['userID'];
				$savetable->trueName = $arg_array['trueName'];
				$savetable->mobile = $arg_array['mobile'];
				$savetable->phone = $arg_array['phone'];
				$savetable->email = $arg_array['email'];
				$savetable->useFlg = $arg_array['useFlg'];
				$savetable->merchantName = $arg_array['merchantName'];
				if(!empty($arg_array['userPwd']))
				$savetable->userPwd = md5($arg_array['userPwd']);

				$this->dbca->save($savetable);
				return array( 'code' => 200, 'message' => '保存成功' );
			}else{
				return array('code'=>400,'message'=>'用户名不存在');
			}
		}catch (Exception $e) {

			error_log($e->getMessage());
			return array( 'code' => 500, 'message' => '系统错误' );

		}

	}

	/**
     * 删除用户
     * @param $arg_array
     * $arg_array = array(
     * 'delete_str' => 用户名
     * )
     * @return array
     */
	public function deleteUser ( $arg_array ) {

		//将字符串截成数组
		$delete_array = explode('_', $arg_array['delete_str']);

		try {

			foreach($delete_array as $val){
				$this->dbca->stmt_query('DELETE FROM mall_merchant_user WHERE userID = ?','s',$val);
			}

			return array( 'code' => 200, 'message' => '分类删除成功');

		} catch (Exception $e) {
			error_log($e->getMessage());
			return array( 'code' => 400, 'message' => '系统错误' );
		}
	}

	/**
     * 用户禁用 使用
     * @param $arg_array
     * $arg_array = array(
            'userID' => 用户名，
            'useFlg' => 禁用使用标志
     * )
     * @return array
     */
	public function userAction($arg_array) {

		$merchant_user = new entity('mall_merchant_user');
		$merchant_user->userID = $arg_array['userID'];
		if($this->dbca->fetch($merchant_user)){
			$merchant_user->useFlg = $arg_array['useFlg'];
			$this->dbca->save($merchant_user);
		}else{
			return array('code'=>400,'message'=>'不存在用户');
		}

		return array('code'=>200,'message'=>'用户使用状态更新成功');
	}

	/**
     * 查询商户促销信息
     * @param $arg_array
     * @return array|null
     */
	public function searchMerchantPromotion( &$arg_array ){

		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

		//商户ID
		if (isset($arg_array['merchantID']) && is_numeric($arg_array['merchantID'])) {
			$sql .= ' AND merchantID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['merchantID'];
		}

		//促销活动ID
		if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
			$sql .= ' AND promotionID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['promotionID'];
		}

		//促销活动名称
		if (isset($arg_array['promotionName']) && !empty($arg_array['promotionName']) ) {
			$sql .= ' AND promotionName LIKE ?';
			$params_type .= 's';
			$params_array[] = '%'.trim($arg_array['promotionName']).'%';
		}

		//促销活动开始时间
		if (isset($arg_array['startDate']) && !empty($arg_array['startDate']) ) {
			$sql .= ' AND startDate <= ?';
			$params_type .= 's';
			$params_array[] = trim($arg_array['startDate']);
		}

		//促销活动结束时间
		if (isset($arg_array['endDate']) && !empty($arg_array['endDate']) ) {
			$sql .= ' AND endDate >= ?';
			$params_type .= 's';
			$params_array[] = trim($arg_array['endDate']);
		}

		//使用状态
		if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1)) ) {
			$sql .= ' AND useFlg = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['useFlg'];
		}

        //审核状态
        if (isset($arg_array['promotionStatus']) && in_array($arg_array['promotionStatus'], array(0, 1)) ) {
            $sql .= ' AND promotionStatus = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionStatus'];
        }

		if ($sql) {
			$sql = 'WHERE ' . substr($sql, 4);
		}

		try {

			if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

				//统计分类数量
				$search_sql = 'SELECT COUNT(*) AS item_count FROM mall_merchant_promotion ' . $sql;
				$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				$item_count = $count_array[0]->item_count;
				if ($item_count == 0) {
					$arg_array['count'] = 0;
					return null;
				}

				$arg_array['count'] = $item_count;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

				//分页
				if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				$arg_array['page'] = 1;

				$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

			} else {

				$arg_array['count'] = 0;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

			}

			//查询信息
			$search_sql = 'SELECT * FROM mall_merchant_promotion ' . $sql;
			$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
			if (!$temp_item_array)
			return null;

			foreach($temp_item_array as &$item) {
				$item_array[] = array(
				'merchantID' => $item->merchantID,
				'promotionID' => $item->promotionID,
				'promotionName' => $item->promotionName,
				'startDate' => $item->startDate,
				'endDate' => $item->endDate,
				'description' => $item->description,
				'useFlg' => $item->useFlg,
				'promotionStatus' => $item->promotionStatus
				);
			}

			return $item_array;

		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}

	/**
     * 查询订阅信息
     * @param $arg_array
     * @return array|null
     */
	public function searchMerchantSubscribe( &$arg_array ) {

		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

		//商户ID
		if (isset($arg_array['merchantID']) && is_numeric($arg_array['merchantID'])) {
			$sql .= ' AND merchantID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['merchantID'];
		}

		//订阅会员号
		if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
			$sql .= ' AND pcustID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['pcustID'];
		}

		//会员名
		if (isset($arg_array['custID']) && !empty($arg_array['custID']) ) {
			$sql .= ' AND custID = ?';
			$params_type .= 's';
			$params_array[] = trim($arg_array['custID']);
		}

		if ($sql) {
			$sql = 'WHERE ' . substr($sql, 4);
		}

		try {

			if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

				//统计分类数量
				$search_sql = 'SELECT COUNT(*) AS item_count FROM mall_merchant_subscribe_detail ' . $sql;
				$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				$item_count = $count_array[0]->item_count;
				if ($item_count == 0) {
					$arg_array['count'] = 0;
					return null;
				}

				$arg_array['count'] = $item_count;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

				//分页
				if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				$arg_array['page'] = 1;

				$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

			} else {

				$arg_array['count'] = 0;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

			}

			//查询信息
			$search_sql = 'SELECT * FROM mall_merchant_subscribe_detail ' . $sql;
			$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
			if (!$temp_item_array)
			return null;

			foreach($temp_item_array as &$item) {
				$item_array[] = array(
				'creator' => $item->creator,
				'createTime' => $item->createTime,
				'pcustID' => $item->pcustID,
				'custID' => $item->custID,
				'merchantID' => $item->merchantID
				);
			}

			return $item_array;

		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}

	/**
     * 保存订阅信息
     * @param $arg_array
     * @return array|null
     */
	public function saveSubscribe( $arg_array ) {

		if( !isset($arg_array['userID'] , $arg_array['merchantID']) || empty($arg_array['userID']) || empty($arg_array['merchantID']) )
		return array( 'code'=>400 , 'message'=>'订阅失败' );

		if( !is_numeric($arg_array['userID']) || !is_numeric($arg_array['merchantID']) )
		return array( 'code'=>400 , 'message'=>'订阅失败' );

		//查询用户信息
		$search_user = 'SELECT * FROM cust_master WHERE pcustID=?';
		$userInfo    = $this->dbca->stmt_query($search_user,'i',$arg_array['userID']);

		if( empty($userInfo) )
		return array( 'code'=>404 , 'message'=>'订阅失败' );

		//查询商户信息
		$getMerchantInfo = $this->searchMerchantInfo($arg_array);

		if( empty($getMerchantInfo) )
		return array( 'code'=>404 , 'message'=>'没有找到门店信息' );

		//查询用户是否已经订阅过该门店
		$check_array = array(
		'pcustID' => $arg_array['userID'],
		'merchantID' => $arg_array['merchantID']
		);

		$check_result = $this->searchMerchantSubscribe($check_array);

		if( $check_result )
		return array( 'code'=>400 , 'message'=>'您已订阅该门店' );

		try{

			//保存订阅信息
			$subscribe_obj = new entity('mall_merchant_subscribe_detail');
			$subscribe_obj->creator = $arg_array['userID'];
			$subscribe_obj->pcustID = $arg_array['userID'];
			$subscribe_obj->custID = $userInfo[0]->custID;
			$subscribe_obj->merchantID = $arg_array['merchantID'];

			//保存
			$this->dbca->save( $subscribe_obj );

			return array( 'code'=>200 , 'message'=>'订阅成功' ,'data'=>array('merchant_id'=>$getMerchantInfo[0]['merchantID'],'merchant_name'=>$getMerchantInfo[0]['merchantName']));

		}catch(Exception $e){

			error_log( $e->getMessage() );
			return array( 'code'=>500 , 'message'=>'系统错误，订阅失败' );

		}

	}
	
	/**
     * 保存订阅信息
     * @param $arg_array
     * @return array|null
     */
	public function saveSubscribeMall( $arg_array ) {

		if( !isset($arg_array['userID'] , $arg_array['merchantID']) || empty($arg_array['userID']) || empty($arg_array['merchantID']) )
		return array( 'code'=>400 , 'message'=>'订阅失败' );

		if( !is_numeric($arg_array['userID']) || !is_numeric($arg_array['merchantID']) )
		return array( 'code'=>400 , 'message'=>'订阅失败' );

		//查询用户信息
		$search_user = 'SELECT * FROM cust_master WHERE pcustID=?';
		$userInfo    = $this->dbca->stmt_query($search_user,'i',$arg_array['userID']);

		if( empty($userInfo) )
		return array( 'code'=>404 , 'message'=>'订阅失败' );

		//查询商户信息
		$arg_array['mallID'] = $arg_array['merchantID'];
		$getMerchantInfo = $this->searchMall( $arg_array );

		if( empty($getMerchantInfo) )
		return array( 'code'=>404 , 'message'=>'没有找到门店信息' );

		//查询用户是否已经订阅过该门店
		$check_array = array(
		'pcustID' => $arg_array['userID'],
		'merchantID' => $arg_array['merchantID']
		);

		$check_result = $this->searchMerchantSubscribe($check_array);

		if( $check_result )
		return array( 'code'=>400 , 'message'=>'您已订阅该门店' );

		try{

			//保存订阅信息
			$subscribe_obj = new entity('mall_merchant_subscribe_detail');
			$subscribe_obj->creator = $arg_array['userID'];
			$subscribe_obj->pcustID = $arg_array['userID'];
			$subscribe_obj->custID = $userInfo[0]->custID;
			$subscribe_obj->merchantID = $arg_array['mallID'];

			//保存
			$this->dbca->save( $subscribe_obj );

			return array( 'code'=>200 , 'message'=>'订阅成功' ,'data'=>array('merchant_id'=>$getMerchantInfo[0]['mallID'],'merchant_name'=>$getMerchantInfo[0]['mallName']));

		}catch(Exception $e){

			error_log( $e->getMessage() );
			return array( 'code'=>500 , 'message'=>'系统错误，订阅失败' );

		}

	}

	/**
     * 取消订阅信息
     * @param $arg_array
     * @return array|null
     */
	public function cancelSubscribe( $arg_array ) {

		if( !isset($arg_array['userID'] , $arg_array['merchantID']) || empty($arg_array['userID']) || empty($arg_array['merchantID']) )
		return array( 'code'=>400 , 'message'=>'取消订阅失败' );

		if( !is_numeric($arg_array['userID']) || !is_numeric($arg_array['merchantID']) )
		return array( 'code'=>400 , 'message'=>'取消订阅失败' );

		//查询用户信息
		$search_user = 'SELECT * FROM cust_master WHERE pcustID=?';
		$userInfo    = $this->dbca->stmt_query($search_user,'i',$arg_array['userID']);

		if( empty($userInfo) )
		return array( 'code'=>404 , 'message'=>'取消订阅失败' );

		//查询门店信息
		$getMerchantInfo = $this->searchMerchantInfo($arg_array);

		if( empty($getMerchantInfo) )
		return array( 'code'=>404 , 'message'=>'没有找到门店信息' );

		try{

			//保存订阅信息
			$subscribe_obj = new entity('mall_merchant_subscribe_detail');
			$subscribe_obj->pcustID = $arg_array['userID'];
			$subscribe_obj->merchantID = $arg_array['merchantID'];

			if( !$this->dbca->fetch($subscribe_obj) )
			return array( 'code'=>404 , 'message'=>'没有找到订阅信息' );

			//保存
			$this->dbca->delete( $subscribe_obj );

			return array( 'code'=>200 , 'message'=>'取消订阅成功' ,'data'=>array('merchant_id'=>$getMerchantInfo[0]['merchantID'],'merchant_name'=>$getMerchantInfo[0]['merchantName']));

		}catch(Exception $e){

			error_log( $e->getMessage() );
			return array( 'code'=>500 , 'message'=>'系统错误，取消失败' );

		}

	}

	public function cateMaxOrder($cateFlg) {

		$maxSortOrder = '';
		switch ($cateFlg){
			case 1:	//一级分类
			$maxSortOrder = $this->dbca->stmt_query('SELECT IF(MAX(sortOrder) IS NULL ,1 , MAX(sortOrder)+1) AS max_sortOrder FROM mall_bigCategory');
			break;
			case 2:	//二级分类
			$maxSortOrder = $this->dbca->stmt_query('SELECT IF(MAX(sortOrder) IS NULL ,1 , MAX(sortOrder)+1) AS max_sortOrder FROM mall_midCategory');
			break;
		}

		return $maxSortOrder;
	}


	/**
     * 获取商户信息
     * @param array $arg_array    查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * 
     *       'mallID'=> int 门店ID
     * 		 'merchantID' => int 商户ID
     * 		 'useFlg' => int 使用标识
     * 		 'extend_sort'=> array(array('sortname'=>'','soryby'=>''),array('sortname'=>'','soryby'=>'')); 扩展排序字段
     * )
     * @return null|array
     */
	public function searchMerchantInfo(&$arg_array) {

		$sql = '';//sql语句

		$param_type = '';//类型

		$param_data = array(); //数据

		if(isset($arg_array['mallID']) && $arg_array['mallID'] >0){
			$sql .= ' AND mallID = ? ';
			$param_type .= 'i';
			$param_data[] = $arg_array['mallID'];
		}

		if(isset($arg_array['merchantName']) && !empty($arg_array['merchantName'])){
			$sql .= ' AND merchantName LIKE ? ';
			$param_type .= 's';
			$param_data[] = '%'.$arg_array['merchantName'].'%';
		}

		if(isset($arg_array['merchantID']) && !empty($arg_array['merchantID'])){
			$sql .= ' AND merchantID = ? ';
			$param_type .= 'i';
			$param_data[] = $arg_array['merchantID'];
		}

		if(isset($arg_array['buildingID']) && $arg_array['buildingID'] > 0){
			$sql .= ' AND buildingID = ? ';
			$param_type .= 'i';
			$param_data[] = $arg_array['buildingID'];
		}

		if(isset($arg_array['floor']) && $arg_array['floor'] > 0){
			$sql .= ' AND floor = ? ';
			$param_type .= 'i';
			$param_data[] = $arg_array['floor'];
		}

		if(isset($arg_array['bigCategoryID']) && $arg_array['bigCategoryID'] > 0){
			$sql .= ' AND bigCategoryID = ? ';
			$param_type .= 'i';
			$param_data[] = $arg_array['bigCategoryID'];
		}

		if(isset($arg_array['midCategoryID']) && $arg_array['midCategoryID'] > 0){
			$sql .= ' AND midCategoryID = ? ';
			$param_type .= 'i';
			$param_data[] = $arg_array['midCategoryID'];
		}

		if(isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg'])){
			$sql .= ' AND useFlg = ? ';
			$param_type .= 'i';
			$param_data[] = $arg_array['useFlg'];
		}
		if($sql){
			$sql = 'WHERE'.substr($sql,4);
		}

		try{
			//查询门店总量
			if(isset($arg_array['rp']) && $arg_array['rp'] >1){
				$searchStr = 'SELECT COUNT(*) AS item_count FROM mall_merchant_master '.$sql;

				$count_array = $this->dbca->stmt_query($searchStr,$param_type,$param_data);

				$count = $count_array[0]->item_count;
				if($count == 0){
					$arg_array['count'] = 0;
					return null;
				}
				$arg_array['count'] = $count;

				if(isset($arg_array['sortname']) && !empty($arg_array['sortname'])){
					$sql .= sprintf(' ORDER BY %s %s',$arg_array['sortname'],$arg_array['sortorder']);
				}
				//分页
				if(isset($arg_array['page']) && $arg_array['page'] > 0){
					$sql .= sprintf(' LIMIT %d, %d',($arg_array['page']-1)*$arg_array['rp'],$arg_array['rp']);
				}

			}else{
				$arg_array['count'] = 0;
				//排序
				if(isset($arg_array['sortname']) && !empty($arg_array['sortname'])){
					$sql .= sprintf(' ORDER BY %s %s',$arg_array['sortname'],$arg_array['sortorder']);
				}

				//added by yinfulin 2013-11-26
				if (isset($arg_array['extend_sort']) && is_array($arg_array['extend_sort']) && (count($arg_array['extend_sort']) > 0)) {
					foreach ($arg_array['extend_sort'] as $sort_val){
						$sql .= sprintf(', %s %s',$sort_val['sortname'],$sort_val['sortorder']);
					}
				}
			}

			$searchStr = 'SELECT * FROM mall_merchant_master '.$sql;

			$merchantInfo = $this->dbca->stmt_query($searchStr,$param_type,$param_data);

			if($merchantInfo){

				foreach($merchantInfo as $item){
					$result_array[] =array(
					'merchantID'   => $item->merchantID,
					'merchantName' => $item->merchantName,
					'phone'        => $item->phone,
					'mobile'       => $item->mobile,
					'logo'         => $item->logo ? G_IMAGE_URL . $item->logo : '',
					'breif'        => $item->breif,
					'description'  => $item->description,
					'mallID'       => $item->mallID,
					'mallName'     => $item->mallName,
					'bigCategoryID'=> $item->bigCategoryID,
					'bigCategoryName'=> $item->bigCategoryName,
					'midCategoryID' =>$item->midCategoryID,
					'midCategoryName'=> $item->midCategoryName,
					'provinceid'     =>$item->provinceid,
					'provinceName'   =>$item->provinceName,
					'cityid'         =>$item->cityid,
					'cityName'       =>$item->cityName,
					'countyid'       =>$item->countyid,
					'countyName'     =>$item->countyName,
					'latitude'       =>$item->latitude,
					'longitude'      =>$item->longitude,
					'buildingID'     =>$item->buildingID,
					'buildingName'   =>$item->buildingName,
					'floor'          =>$item->floor,
					'houseNumber'    =>$item->houseNumber,
					'consumerPrice'  =>$item->consumerPrice,
					'ratings'        =>$item->ratings,
					'environment'    =>$item->environment,

					'useFlg'         =>$item->useFlg
					);
				}

				return $result_array;

			}

		}catch(Exception $e){
			error_log($e->getMessage());
			return null;
		}
	}

	/**
	 * 查询楼层数
	 * @param buildingID
	 */
	public function searchFloor(&$arg_array) {
		if(isset($arg_array['buildingID']) && is_numeric($arg_array['buildingID'])){
			$result = $this->dbca->stmt_query('SELECT floor FROM mall_building WHERE buildingID = ?','i',$arg_array['buildingID']);
			if($result){
				$floor = array(
				'floor' => $result[0]->floor,
				);
				return $floor;
			}
		}else{
			return array('code' => 400, 'message' => '请输入正确的楼宇');
		}
	}

	/**
	 * 根据mallID查询出门店相对应的一级分类
	 */
	public function searchBigCategoryMap(&$arg_array){
		if(isset($arg_array['mallID']) && is_numeric($arg_array['mallID'])){
			$result = $this->dbca->stmt_query('SELECT bigCategoryID FROM mall_category_map WHERE mallID = ? GROUP BY bigCategoryID','i',$arg_array['mallID']);
			if($result){
				foreach($result as $bigCategoryID){
					$bigCategoryName = $this->dbca->stmt_query('SELECT bigCategoryName FROM mall_bigCategory WHERE bigCategoryID = ?','i',$bigCategoryID->bigCategoryID);
					$result_array[] = array(
					'bigCategoryID' => $bigCategoryID->bigCategoryID,
					'bigCategoryName' => $bigCategoryName[0]->bigCategoryName
					);
				}
				//error_log(print_r($result_array,true));
				return $result_array;
			}
		}else{
			return array('code' => 400, 'message' => '门店不存在');
		}
	}

	/**
	 * 根据大分类id找寻出中分类
	 * @param bigCategoryID,mallID,
	 */
	public function searchMidCategoryMap(&$arg_array) {
		if(isset($arg_array['bigCategoryID']) && is_numeric($arg_array['bigCategoryID'])){
			$midCategoryID = $this->dbca->stmt_query('SELECT midCategoryID FROM mall_category_map WHERE bigCategoryID = ? AND mallID = ?','ii',array($arg_array['bigCategoryID'],$arg_array['mallID']));
			if($midCategoryID){
				foreach($midCategoryID as $mid){
					$midCategoryID = $mid->midCategoryID;
					$midCategoryName = $this->dbca->stmt_query('SELECT midCategoryName FROM mall_midCategory WHERE midCategoryID = ?','i',$midCategoryID);
					$result_array[] = array(
					'midCategoryID' => $mid->midCategoryID,
					'midCategoryName' => $midCategoryName[0]->midCategoryName,
					);
				}
				return $result_array;
			}
		}else{
			return array('code' => 400, 'message' => '请选择正确的大分类号');
		}
	}

	/**
	 * 删除商户
	 */
	public function deleteMerchant($arg_array) {

		try{
			$this->dbca->beginTransaction();
			foreach($arg_array as $k){
				$mall_merchant_master = new entity('mall_merchant_master');
				$mall_merchant_master->merchantID = $k;
				if($this->dbca->fetch($mall_merchant_master)){
					$this->dbca->delete($mall_merchant_master,'merchant');
				}
			}
			$this->dbca->commit();
			return array( 'code' => 200, 'message' => '删除成功' );

		}catch(Exception $e){
			$this->dbca->rollBack();
			error_log($e->getMessage());
		}
	}

	/**
     * 修改商户使用状态
     * $arg_array = array(
     * 		id => useFlg
     * )
     */
	public function merchantChangeStatus($arg_array) {

		//参数检查
		if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '') {
			return array( 'code' => 400, 'message' => '缺少参数' );
		}


		$str_array = explode('_', $arg_array['useFlg_str']);

		try{
			//检查商户是否存在或已经被操作
			$mall_merchant_master = new entity('mall_merchant_master');
			$mall_merchant_master->merchantID = $str_array[0] ;
			if (!$this->dbca->fetch( $mall_merchant_master )){
				throw new Exception(sprintf('商户号「%d」,的商户不存在,请审核后再操作',$str_array[0]) , 400) ;
			}

			//检查商户状态是否已经被修改
			if($mall_merchant_master->useFlg == $str_array[1] && $str_array[1] == 1){
				throw new Exception(sprintf('商户号「%d」,的商户已启用',$str_array[0]) , 400) ;
			}

			if($mall_merchant_master->useFlg == $str_array[1] && $str_array[1] == 0){
				throw new Exception(sprintf('商户号「%d」,的商户已禁用',$str_array[0]) , 400) ;
			}

			//保存
			$mall_merchant_master->useFlg = $str_array[1] ;
			$this->dbca->save( $mall_merchant_master , 'mall_merchant_master' );

		}catch (Exception $e) {
			if ($e->getCode() > 0){
				return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
			}else {
				error_log($e->getMessage());
				return array( 'code' => 500, 'message' => '系统错误' );
			}
		}

		if($str_array[1] == 1){
			return array( 'code' => 200, 'message' => '商户启用成功' );
		}else if ($str_array[1] == 0){
			return array( 'code' => 200, 'message' => '商户禁用成功' );
		}
	}

	/**
     * 获取会员订阅商户表
     * @param $arg_array
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     *
     * 		 'merchantID' => int 商户ID
     * )
     * @return array|null
     */
	public function getSubscribe(&$arg_array){

		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

		//商户ID
		if(isset($arg_array['merchantID']) && !empty($arg_array['merchantID'])){
			$sql .= ' AND merchantID = ? ';
			$params_type .= 'i';
			$params_array[] = $arg_array['merchantID'];
		}

		if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
			$sql .= $arg_array['extend'];
		}

		if ($sql) {
			$sql = 'WHERE ' . substr($sql, 4);
		}

		try {

			if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

				//统计分类数量
				$search_sql = 'SELECT COUNT(*) AS item_count FROM mall_merchant_subscribe_detail ' . $sql;
				$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				$item_count = $count_array[0]->item_count;
				if ($item_count == 0) {
					$arg_array['count'] = 0;
					return null;
				}

				$arg_array['count'] = $item_count;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

				//分页
				if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				$arg_array['page'] = 1;

				$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

			} else {

				$arg_array['count'] = 0;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

			}

			//查询分类信息
			$search_sql = 'SELECT * FROM mall_merchant_subscribe_detail ' . $sql;
			$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
			if (!$temp_item_array)
			return null;

			foreach($temp_item_array as &$item) {
				$item_array[] = array(
				'createTime' => $item->createTime,
				'pcustID' => $item->pcustID,
				'custID' => $item->custID,
				'merchantID' => $item->merchantID
				);
			}

			return $item_array;

		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}

	/**
     * 删除会员订阅商户表
     * @param $arg_array
     * $arg_array = array (
     *      'delete_str' => string 订阅会员号
     * )
     * @return array|null
     */
	public function deleteSubscribe(&$arg_array){

		$delete_arr = explode('_',$arg_array['delete_str']);
		try {
			foreach($delete_arr as $val){

				$this->dbca->stmt_query('delete from mall_merchant_subscribe_detail where pcustID = ?','i',$val);

			}

			return array('code'=>200,'message'=>'删除成功');

		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}

    /**
     * 获取促销活动列表
     * @param $arg_array
     * * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     *
     * 		 'merchantID' => int 商户ID
     *       'promotionName' => string 活动名称
     *       'startDate' => date 开始日期
     *       'endDate' =>date 结束日期
     *       'promotionID' => int 促销活动ID
     *       'useFlg' => int 使用状态
     * )
     * @return array|null
     */
    public function searchPromotionList(&$arg_array){


        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //商户ID
        if (isset($arg_array['merchantID']) && is_numeric($arg_array['merchantID'])) {
            $sql .= ' AND merchantID = ? ';
            $params_type .= 'i';
            $params_array[] = $arg_array['merchantID'];
        }

        //审核状态
        if (isset($arg_array['promotionStatus']) && in_array($arg_array['promotionStatus'],array(0,1))) {
            $sql .= ' AND promotionStatus = ? ';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionStatus'];
        }

        //促销活动想状态
        $status = '全部';

        //活动名称
        if (isset($arg_array['promotionName']) && !empty($arg_array['promotionName'])) {
            $sql .= ' AND promotionName like ? ';
            $params_type .= 's';
            $params_array[] = '%'.$arg_array['promotionName'].'%';
        }

        //状态
        if (isset($arg_array['status']) && in_array($arg_array['status'],array(0,1,2))) {

            switch($arg_array['status']){
                case 0:
                    $sql .= ' AND endDate < ? ';
                    $params_type .= 's';
                    $params_array[] = date('y-m-d');
                    $status = '已结束';
                    break;
                case 1:
                    $sql .= ' AND startDate <= ? ';
                    $params_type .= 's';
                    $params_array[] = date('y-m-d');
                    $sql .= ' AND endDate >= ? ';
                    $params_type .= 's';
                    $params_array[] = date('y-m-d');
                    $status = '活动中';
                    break;
                case 2:
                    $sql .= ' AND startDate > ? ';
                    $params_type .= 's';
                    $params_array[] = date('y-m-d');
                    $status = '未开始';
                    break;
            }
        }

        //促销活动ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ? ';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        //使用状态
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ? ';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM mall_merchant_promotion ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM mall_merchant_promotion ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'merchantID' => $item->merchantID,
                    'promotionID' => $item->promotionID,
                    'promotionName' => $item->promotionName,
                    'startDate' => $item->startDate,
                    'endDate' => $item->endDate,
                    'description' => $item->description,
                    'useFlg' => $item->useFlg,
                    'status' => $status,
                    'promotionStatus' => $item->promotionStatus
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

	/**
     * 促销活动添加
     * @param $arg_array
     * $arg_array = array(
     *          'merchantID' => int 商户号
     *          'creator' => string 创建人
     *          'promotionName' => string 促销活动名称
     *          'startDate' => date 开始日期
     *          'endDate' => date 结束日期
     *          'description' => text 描述
     *          'useFlg' => int 使用状态
     * )
     * @return array|null
     */
	public function promotionAdd(&$arg_array){

		if(!isset($arg_array['promotionName']) && empty($arg_array['promotionName']))
		return array('code'=>400,'message'=>'促销活动名称为空');


		if(!isset($arg_array['startDate']) && empty($arg_array['startDate']))
		return array('code'=>400,'message'=>'开始时间为空');

		if(!isset($arg_array['endDate']) && empty($arg_array['endDate']))
		return array('code'=>400,'message'=>' 结束时间为空');

		if($arg_array['startDate'] > $arg_array['endDate'])
		return array('code'=>400,'message'=>' 开始时间大于结束时间');


		try {
			$promotion = new entity('mall_merchant_promotion');

			$promotion->merchantID = $arg_array['merchantID'];
			$promotion->creator = $arg_array['creator'];
			$promotion->promotionName = $arg_array['promotionName'];
			$promotion->startDate = $arg_array['startDate'];
			$promotion->endDate = $arg_array['endDate'];
			$promotion->description = $arg_array['description'];
			$promotion->useFlg = $arg_array['useFlg'];

			$this->dbca->save($promotion);

			return array('code'=>200,'message'=>'保存成功');

		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}
	}

	/**
     * 促销活动编辑
     * @param $arg_array
     * * $arg_array = array(
     *          'merchantID' => int 商户号
     *          'creator' => string 创建人
     *          'promotionName' => string 促销活动名称
     *          'startDate' => date 开始日期
     *          'endDate' => date 结束日期
     *          'description' => text 描述
     *          'useFlg' => int 使用状态
     * )
     * @return array|null
     */
	public function promotionEdit(&$arg_array){

		if(!isset($arg_array['promotionID']) && empty($arg_array['promotionID']))
		return array('code'=>400,'message'=>'参数错误');

		if(!isset($arg_array['promotionName']) && empty($arg_array['promotionName']))
		return array('code'=>400,'message'=>'促销活动名称为空');


		if(!isset($arg_array['startDate']) && empty($arg_array['startDate']))
		return array('code'=>400,'message'=>'开始时间为空');

		if(!isset($arg_array['endDate']) && empty($arg_array['endDate']))
		return array('code'=>400,'message'=>' 结束时间为空');

		if($arg_array['startDate'] > $arg_array['endDate'])
		return array('code'=>400,'message'=>' 开始时间大于结束时间');

		try {
			$promotion = new entity('mall_merchant_promotion');
			$promotion->promotionID = $arg_array['promotionID'];
			if($this->dbca->fetch($promotion)){
				$promotion->creator = $arg_array['creator'];
				$promotion->promotionName = $arg_array['promotionName'];
				$promotion->startDate = $arg_array['startDate'];
				$promotion->endDate = $arg_array['endDate'];
				$promotion->description = $arg_array['description'];
				$promotion->useFlg = $arg_array['useFlg'];

				$this->dbca->save($promotion);
			}else{
				return array('code'=>400,'message'=>'促销活动不存在');
			}

			return array('code'=>200,'message'=>'保存成功');

		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}

	/**
     * 促销活动禁用使用
     * @param $arg_array
     * * $arg_array = array(
     *          'promotionID' => int 促销活动ID
     *          'useFlg' => int 使用状态
     * )
     * @return array
     */
	public function promotionAction(&$arg_array){

		$promotion = new entity('mall_merchant_promotion');
		$promotion->promotionID = $arg_array['promotionID'];

		try{
			if($this->dbca->fetch($promotion)){
				$promotion->useFlg = $arg_array['useFlg'];
				$this->dbca->save($promotion);
			}else{
				return array('code'=>400,'message'=>'不存在促销活动');
			}

			return array('code'=>200,'message'=>'促销活动状态更新成功');
		}catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}

	/**
     * 促销活动删除
     * @param $arg_array
     * $arg_array = array(
     *          'delete_str' => string 促销活动ID
     * )
     * @return array|null
     */
	public function promotionDelete(&$arg_array){

		if(!isset($_REQUEST['delete_str']) || empty($_REQUEST['delete_str']))
		return array('code'=>400,'message'=>'请选择删除促销活动');

		$delete_arr = explode('_',$arg_array['delete_str']);

		try{

			foreach($delete_arr as $val){
				$this->dbca->stmt_query('delete from mall_merchant_promotion where promotionID = ?','i',$val);
			}
			return array('code'=>200,'message'=>'删除成功');
		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}


	/**
	 * 保存预约信息
	 * @param arg_array
	 */
    public function saveReserveInfo(&$arg_array) {

        if(!isset($arg_array['title'],$arg_array['startDate'],$arg_array['endDate'],$arg_array['startTime'],$arg_array['endTime'],$arg_array['useFlg'],$arg_array['merchantID'])){
            return array('code' => 400,'message' => '参数错误');
        }

        if(empty($arg_array['title'])){
            return array('code' => 400,'message' => '预约名称不能为空');
        }

        if(empty($arg_array['startDate'])){
            return array('code' => 400,'message' => '开始时间不能为空');
        }

        if(empty($arg_array['endDate'])){
            return array('code' => 400,'message' => '结束时间不能为空');
        }

        if(empty($arg_array['startTime'])){
            return array('code' => 400,'message' => '开始时间段不能为空');
        }

        if(empty($arg_array['endTime'])){
            return array('code' => 400,'message' => '结束时间段不能为空');
        }

        if(!is_numeric($arg_array['useFlg'])){
            return array('code' => 400,'message' => '使用状态不能为空');
        }

        if($arg_array['startDate'] > $arg_array['endDate']){
            return array('code' => 400,'message' => '开始时间不能大于结束时间');
        }

        if($arg_array['startTime'] < 0 && $arg_array['startTime']){
            return array('code' => 400,'message' => '开始时间段错误,请检查');
        }

        if($arg_array['endTime'] <0 && $arg_array['endTime'] > 24){
            return array('code' => 400,'message' => '结束时间段错误,请检查');
        }

        if($arg_array['startTime'] > $arg_array['endTime']){
            return array('code' => 400,'message' => '开始时间段不能大于结束时间段');
        }

        try{
            $mall_merchant_reserve = new entity('mall_merchant_reserve');
            if (!empty($arg_array['reserveID']) && $arg_array['reserveID'] > 0) {//修改
                $mall_merchant_reserve->reserveID = $arg_array['reserveID'];
                if (!$this->dbca->fetch($mall_merchant_reserve)) {
                    throw new Exception('预约信息信息没有找到', 404);
                }
            } else {//增加

                $mall_merchant_reserve->creator = $arg_array['creator'];

            }

            $mall_merchant_reserve->merchantID = $arg_array['merchantID'];
            $mall_merchant_reserve->title = $arg_array['title'];
            $mall_merchant_reserve->startDate = $arg_array['startDate'];
            $mall_merchant_reserve->endDate = $arg_array['endDate'];
            $mall_merchant_reserve->startTime = $arg_array['startTime'];
            $mall_merchant_reserve->endTime = $arg_array['endTime'];
            $mall_merchant_reserve->description = $arg_array['description'];
            $mall_merchant_reserve->useFlg = $arg_array['useFlg'];

            $this->dbca->save($mall_merchant_reserve);

            $insert_id = $this->dbca->insert_id;

            $merchant_reserve = $this->dbca->stmt_query('SELECT * FROM mall_merchant_reserve mmr INNER JOIN mall_merchant_subscribe_detail mmsd ON mmr.merchantID = mmsd.merchantID where mmr.reserveID = ?','i',$insert_id);

            if($merchant_reserve ){
                foreach($merchant_reserve as $val){
                    $cust_message = new entity('cust_message');
                    $cust_message->creator = $arg_array['creator'];
                    $cust_message->pcustID = $val->pcustID;
                    $cust_message->title = $val->title;
                    $cust_message->message = $val->description;
                    $cust_message->link = '/weixin/wap/reserve_add.html?reserveID='.$val->reserveID;
                    $this->dbca->save($cust_message);
                }
            }

            return array('code' => 200,'message' => '预约信息保存成功');
        }catch(Exception $e){
            error_log($e->getMessage());
        }

    }

	/**
	 * 预约信息删除
	 *
	 */
	public function deleteReserve(&$arg_array) {

		$mall_merchant_reserve = new entity('mall_merchant_reserve');

		try{
			$this->dbca->beginTransaction();
			foreach($arg_array as $k){
				$mall_merchant_reserve->reserveID = $k;
				if($this->dbca->fetch($mall_merchant_reserve)){
					$this->dbca->delete($mall_merchant_reserve,'reserve');
				}
			}
			$this->dbca->commit();
			return array( 'code' => 200, 'message' => '删除成功' );

		}catch(Exception $e){
			$this->dbca->rollBack();
			error_log($e->getMessage());
		}

	}
	/**
     * 修改预约使用状态
     * $arg_array = array(
     * 		id => useFlg
     * )
     */
	public function reserveChangeStatus($arg_array) {

		//参数检查
		if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '') {
			return array( 'code' => 400, 'message' => '缺少参数' );
		}


		$str_array = explode('_', $arg_array['useFlg_str']);

		try{
			//检查商户是否存在或已经被操作
			$mall_merchant_reserve = new entity('mall_merchant_reserve');
			$mall_merchant_reserve->reserveID = $str_array[0] ;
			if (!$this->dbca->fetch( $mall_merchant_reserve )){
				throw new Exception(sprintf('预约号「%d」,的预约不存在,请审核后再操作',$str_array[0]) , 400) ;
			}

			//检查商户状态是否已经被修改
			if($mall_merchant_reserve->useFlg == $str_array[1] && $str_array[1] == 1){
				throw new Exception(sprintf('预约号「%d」,的预约已启用',$str_array[0]) , 400) ;
			}

			if($mall_merchant_reserve->useFlg == $str_array[1] && $str_array[1] == 0){
				throw new Exception(sprintf('预约号「%d」,的预约已禁用',$str_array[0]) , 400) ;
			}

			//保存
			$mall_merchant_reserve->useFlg = $str_array[1] ;
			$this->dbca->save( $mall_merchant_reserve , 'mall_merchant_reserve' );

		}catch (Exception $e) {
			if ($e->getCode() > 0){
				return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
			}else {
				error_log($e->getMessage());
				return array( 'code' => 500, 'message' => '系统错误' );
			}
		}

		if($str_array[1] == 1){
			return array( 'code' => 200, 'message' => '预约启用成功' );
		}else if ($str_array[1] == 0){
			return array( 'code' => 200, 'message' => '预约禁用成功' );
		}
	}

	/**
	 * 查询预约详情
	 *
	 * @param = array()
	 * 
	 */
    public function searchReserveDetailInfo(&$arg_array){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $param_type = '';

        //参数值数组
        $param_data = array();

        //预约ID
        if (isset($arg_array['reserveID']) && is_numeric($arg_array['reserveID'])) {
            $sql .= ' AND reserveID = ?';
            $param_type .= 'i';
            $param_data[] = $arg_array['reserveID'];
        }

        //用户ID
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $param_type .= 'i';
            $param_data[] = $arg_array['pcustID'];
        }

        //预约详情状态
        if (isset($arg_array['reserve_status']) && is_numeric($arg_array['reserve_status']) && in_array($arg_array['reserve_status'], array(0,1,3))) {
            $sql .= ' AND reserve_status = ?';
            $param_type .= 'i';
            $param_data[] = $arg_array['reserve_status'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if(isset($arg_array['rp']) && $arg_array['rp'] >1){
                $searchStr = "SELECT COUNT(*) AS item_count FROM mall_merchant_reserve_user_detail ".$sql;


                $count_array = $this->dbca->stmt_query($searchStr,$param_type,$param_data);


                $count = $count_array[0]->item_count;
                if($count == 0){
                    $arg_array['count'] = 0;
                    return null;
                }
                $arg_array['count'] = $count;

                if(isset($arg_array['sortname']) && !empty($arg_array['sortname'])){
                    $sql .= sprintf(' ORDER BY %s %s',$arg_array['sortname'],$arg_array['sortorder']);
                }
                //分页
                if(isset($arg_array['page']) && $arg_array['page'] > 0){
                    $sql .= sprintf(' LIMIT %d, %d',($arg_array['page']-1)*$arg_array['rp'],$arg_array['rp']);
                }

            }else{
                $arg_array['count'] = 0;
                //排序
                if(isset($arg_array['sortname']) && !empty($arg_array['sortname'])){
                    $sql .= sprintf(' ORDER BY %s %s',$arg_array['sortname'],$arg_array['sortorder']);
                }
            }

            //查询信息
            $search_sql = 'SELECT * FROM mall_merchant_reserve_user_detail ' . $sql;

            $temp_item_array = &$this->dbca->stmt_query($search_sql, $param_type, $param_data);
            if ($temp_item_array){

                foreach($temp_item_array as &$item) {

                    $item_array[] = array(
                        'uuid' => $item->uuid,
                        'createTime' => $item->createTime,
                        'reserve_detailID' =>$item->reserve_detailID,
                        'reserveID' => $item->reserveID,
                        'contactor' =>$item->contactor,
                        'mobile'   =>$item->mobile,
                        'phone'    =>$item->phone,
                        'reserved_date' => $item->reserved_date,
                        'reserved_time' => $item->reserved_time,
                        'reserve_number' => $item->reserve_number,
                        'reserve_status' => $item->reserve_status,
                        'merchant_message' => $item->merchant_message,
                        'message' => $item->message,
                        'pcustID' => $item->pcustID
                    );
                }

                return $item_array;
            }

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }

	/**
     * 审核预约信息
     */
    public function reserveDetailReview(&$arg_array){
        //参数检查
        if (!isset($arg_array['reserve_detailID']) || $arg_array['reserve_detailID'] == '') {
            return array( 'code' => 400, 'message' => '缺少参数' );
        }


        $reserve_detailID = $arg_array['reserve_detailID'];

        try{
            //检查商户是否存在或已经被操作

            $mall_merchant_reserve_user_detail = new entity('mall_merchant_reserve_user_detail');
            $mall_merchant_reserve_user_detail->reserve_detailID = $reserve_detailID;
            if(!$this->dbca->fetch($mall_merchant_reserve_user_detail)){
                throw new Exception(sprintf('预约号「%d」,的预约不存在,请审核后再操作',$reserve_detailID),400);
            }

            //检查商户状态是否已经被修改
            if($mall_merchant_reserve_user_detail->reserve_status == 1){
                throw new Exception(sprintf('预约号「%d」,的预约已审核',$reserve_detailID),400);
            }



            //保存
            $mall_merchant_reserve_user_detail->reserve_status = 1 ;

            if($mall_merchant_reserve_user_detail->merchant_message)
                $arg_array['verify_message'] = $mall_merchant_reserve_user_detail->merchant_message .'<br/>'.$arg_array['verify_message'];

            $mall_merchant_reserve_user_detail->merchant_message = $arg_array['verify_message'];
            $result = $this->dbca->save( $mall_merchant_reserve_user_detail);

            return array( 'code' => 200, 'message' => '预约审核通过' );
        }catch (Exception $e) {
            if ($e->getCode() > 0){
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            }else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }

    }

	/**
	 * 取消预约
	 */
    public function reserveDetailCancel(&$arg_array){
        //参数检查

        if (!isset($arg_array['reserve_detailID']) || $arg_array['reserve_detailID'] == '') {
            return array( 'code' => 400, 'message' => '缺少参数' );
        }

        if (!isset($arg_array['reserve_cancel_reason']) || $arg_array['reserve_cancel_reason'] == '') {
            return array( 'code' => 400, 'message' => '缺少参数' );
        }
        $reserve_detailID = $arg_array['reserve_detailID'];

        try{
            //检查商户是否存在或已经被操作

            $mall_merchant_reserve_user_detail = new entity('mall_merchant_reserve_user_detail');
            $mall_merchant_reserve_user_detail->reserve_detailID = $reserve_detailID;
            if(!$this->dbca->fetch($mall_merchant_reserve_user_detail)){
                throw new Exception(sprintf('预约号「%d」,的预约不存在,请审核后再操作',$reserve_detailID),400);
            }

            //检查商户状态是否已经被修改
            if($mall_merchant_reserve_user_detail->reserve_status == 3){
                throw new Exception(sprintf('预约号「%d」,的预约已取消',$reserve_detailID),400);
            }



            //保存
            $mall_merchant_reserve_user_detail->reserve_status = 3 ;

            if($mall_merchant_reserve_user_detail->merchant_message){
                $arg_array['reserve_cancel_reason'] = $mall_merchant_reserve_user_detail->merchant_message.'<br/>'.$arg_array['reserve_cancel_reason'];
            }
            $mall_merchant_reserve_user_detail->merchant_message = $arg_array['reserve_cancel_reason'];
            $result = $this->dbca->save( $mall_merchant_reserve_user_detail);

            return array( 'code' => 200, 'message' => '预约取消成功' );


        }catch (Exception $e) {
            if ($e->getCode() > 0){
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            }else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
    }

	/**
	 * 
	 */
	public function reserveDetailDel(&$arg_array) {

		$mall_merchant_reserve_user_detail = new entity('mall_merchant_reserve_user_detail');

		try{
			$this->dbca->beginTransaction();
			foreach($arg_array as $k){
				$mall_merchant_reserve_user_detail->reserve_detailID = $k;
				if($this->dbca->fetch($mall_merchant_reserve_user_detail)){
					$this->dbca->delete($mall_merchant_reserve_user_detail,'reserve');
				}
			}
			$this->dbca->commit();
			return array( 'code' => 200, 'message' => '删除成功' );

		}catch(Exception $e){
			$this->dbca->rollBack();
			error_log($e->getMessage());
		}

	}

	/**
     * 用户领取优惠券
     */
	public function getCoupon( $arg_array ){

		if (!isset($arg_array['couponID'],$arg_array['userID']) || empty($arg_array['couponID']) || empty($arg_array['userID']) ) {
			return array( 'code' => 400, 'message' => '领取失败' );
		}

		//引用优惠券公共类
		quanli_include('module/base/couponHandler.class.php');

		//实例化优惠券公共类
		$couponHandler = new couponHandler($this->dbca);

		//查询用户信息
		$custMaster = new entity('cust_master');
		$custMaster->pcustID = $arg_array['userID'];

		if( !$this->dbca->fetch($custMaster) )
		    return array( 'code' => 404, 'message' => '领取失败' );

        //查询优惠券信息
        $coupon_obj = new entity('mall_coupon');
        $coupon_obj->couponID = $arg_array['couponID'];

        if( !$this->dbca->fetch($coupon_obj) )
            return array( 'code' => 404, 'message' => '没有找到优惠券信息' );

        if( $coupon_obj->coupon_status == 0 )
            return array( 'code' => 400, 'message' => '该优惠券未通过审核，不可使用' );

		try{

			//保存用户领取优惠券信息
			$user_coupon = new entity('mall_coupon_code');
			$user_coupon->couponID = $arg_array['couponID'];
			$user_coupon->custID   = $custMaster->custID;

			if( $this->dbca->fetch($user_coupon) )
			return array( 'code' => 400, 'message' => '您已领取该优惠券' );

            $user_coupon->creator = $arg_array['userID'];
			$user_coupon->code  = $couponHandler->getCode();  //生成优惠券编码

			$this->dbca->save($user_coupon);

			return array( 'code' => 200, 'message' => '领取成功' );

		}catch(Exception $e){

			error_log( $e->getMessage() );
			return array( 'code' => 200, 'message' => '领取失败' );

		}

	}

	/**
     * 查询优惠券列表
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return array|null
     */
	public function searchCoupon(&$arg_array) {

		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

		//所属门店的ID
		if(isset($arg_array['mallID'])&&!empty($arg_array['mallID'])){
			$sql .= ' AND mallID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['mallID'];
		}

		//优惠券ID
		if (isset($arg_array['couponID']) && is_numeric($arg_array['couponID'])) {
			$sql .= ' AND couponID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['couponID'];
		}

		//优惠券名称
		if(isset($arg_array['couponName']) && !empty($arg_array['couponName']) ){
			$sql .= ' AND couponName LIKE ? ';
			$params_type .= 's';
			$params_array[] = '%' . trim($arg_array['couponName']) . '%';
		}

		//开始日期
		if(isset($arg_array['startDate']) && !empty($arg_array['startDate']) ){
			$sql .= ' AND startDate <= ? ';
			$params_type .= 's';
			$params_array[] = $arg_array['startDate'];
		}

		//结束日期
		if(isset($arg_array['endDate']) && !empty($arg_array['endDate']) ){
			$sql .= ' AND endDate >= ? ';
			$params_type .= 's';
			$params_array[] = $arg_array['endDate'];
		}

		//优惠券发放方式
		if(isset($arg_array['couponType']) && in_array($arg_array['couponType'],array(1,2))){
			$sql .= ' AND couponType = ? ';
			$params_type .= 'i';
			$params_array[] = $arg_array['couponType'];
		}

        //优惠券状态
        if(isset($arg_array['coupon_status']) && in_array($arg_array['coupon_status'],array(0,1))){
            $sql .= ' AND coupon_status = ? ';
            $params_type .= 'i';
            $params_array[] = $arg_array['coupon_status'];
        }

		if ($sql) {
			$sql = ' WHERE ' . substr($sql, 4);
		}


		try {

			if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

				//统计数量
				$search_sql = 'SELECT COUNT(*) AS item_count FROM mall_coupon ' . $sql;
				$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				$item_count = $count_array[0]->item_count;
				if ($item_count == 0) {
					$arg_array['count'] = 0;
					return null;
				}

				$arg_array['count'] = $item_count;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

				//分页
				if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				$arg_array['page'] = 1;

				$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

			} else {

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

			}

			//查询备注信息
			$search_sql = 'SELECT * FROM mall_coupon ' . $sql;
			$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
			if (!$temp_item_array)
			return null;

			if ($temp_item_array) {
				foreach ($temp_item_array as &$item) {
					if ($item->couponType == 1)
					$type_name = '门店优惠券';
					else if ($item->couponType == 2)
					$type_name = '商户优惠券';
					$item_array[] = array(
					'mallID' => $item->mallID,                //门店ID
					'mallName' => $item->mallName,            //门店名称
					'couponID' => $item->couponID,            //ID
					'couponName' => $item->couponName,        //名称
					'startDate' => $item->startDate,          //开始日期
					'endDate' => $item->endDate,              //结束日期
					'couponType' => $item->couponType,        //发放方式
					'amount' => $item->amount,                //优惠券金额
					'limitMoney' => $item->limitMoney,        //订单使用限额
					'codeNum' => $item->codeNum,            //发放数量
					'validity' => $item->validity,            //有效期
					'description' => $item->description,      //描述
					'coupon_status' => $item->coupon_status,     //状态
					'type_name' => $type_name
					);
				}
			}

			return $item_array;

		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}

	/**
     * 审核优惠劵
     * @param $arg_array
     * $arg_array = array(
     *          couponID => 优惠券ID
     * )
     * @return array|null
     */
    public function verifyCoupon(&$arg_array){

        if(!isset($arg_array['couponID']) || empty($arg_array['couponID']))
            return array('code'=> 400,'message'=>'参数传递错误');

        try{
            $coupon = new entity('mall_coupon');
            $coupon->couponID = $arg_array['couponID'];
            if($this->dbca->fetch($coupon)){
                $coupon->coupon_status = 1;
                $this->dbca->save($coupon);
                //会员订阅

                $coupon_merchant = $this->dbca->stmt_query('SELECT mm.couponID,mm.couponName,mm.description,mmsd.pcustID  FROM mall_merchant_subscribe_detail mmsd INNER JOIN (SELECT mc.couponName,mcm.couponID,mc.description,mcm.merchantID FROM mall_coupon_merchant mcm INNER JOIN mall_coupon mc ON mcm.couponID = mc.couponID) AS mm ON mmsd.merchantID = mm.merchantID WHERE mm.couponID=? ','i',$arg_array['couponID']);

                if($coupon_merchant){
                    foreach($coupon_merchant as $val){
                        $cust_message = new entity('cust_message');
                        $cust_message->creator = $arg_array['creator'];
                        $cust_message->pcustID = $val->pcustID;
                        $cust_message->title = $val->couponName;
                        $cust_message->message = $val->description;
                        $cust_message->link = '/weixin/wap/eventCoupon_detail.html?id='.$val->couponID;
                        $this->dbca->save($cust_message);
                    }
                }

                return array('code'=> 200,'message'=>'审核成功');
            }else{
                return array('code'=> 400,'message'=>'没有该优惠劵');
            }
        }catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }

	/**
     * 编辑门店优惠劵
     * @param $arg_array
     * @return array|null
     * $arg_array = array(
            [couponName] => 优惠券名称
            [couponID] => 优惠券ID
            [startDate] => 起始日期
            [endDate] => 结束日期
            [couponType] => 优惠券发放对象
            [limitMoney] => 礼品券使用限额
            [amount] => 优惠券金额
            [codeNum] => 发放数目
            [validity] => 有效期
            [description] => 优惠券描述
            [mallID] => 门店ID
            [creator] => 创建人
            [mallName] => 门店名称
     *      [couponMt] => 判断是否从商户优惠劵改为门店优惠劵
     * )
     */
	public function editCoupon(&$arg_array){

		if(!isset($arg_array['couponID']) || empty($arg_array['couponID']))
		return array( 'code' => 400, 'message' => '参数传递错误' );

		//实例化公共类
		$commHandler = new commHandler();

		if (!isset($arg_array['couponName']) || empty($arg_array['couponName'])) {
			return array( 'code' => 400, 'message' => '优惠券名不能为空' );
		}

		if(!isset($arg_array['startDate']) || empty($arg_array['startDate'])){
			return array( 'code' => 400, 'message' => '优惠券使用开始日期不能为空' );
		}

		if(!isset($arg_array['endDate']) || empty($arg_array['endDate'])){
			return array( 'code' => 400, 'message' => '优惠券使用结束日期不能为空' );
		}

		if ($arg_array['startDate'] > $arg_array['endDate']) {
			return array( 'code' => 400, 'message' => '开始日期不能大于结束日期' );
		}

		if (!isset($arg_array['couponType']) || !in_array($arg_array['couponType'], array(1, 2))) {
			return array( 'code' => 400, 'message' => '请选择优惠券发放方式' );
		}

		if (!isset($arg_array['limitMoney']) || !$commHandler->isMoney($arg_array['limitMoney']) || $arg_array['limitMoney'] < 0) {
			return array( 'code' => 400, 'message' => '订单限额不能为空且必须是大于等于0的数字' );
		}

		if (!isset($arg_array['amount']) || !$commHandler->isMoney($arg_array['amount']) || $arg_array['amount'] <= 0) {
			return array( 'code' => 400, 'message' => '优惠券抵扣金额不能为空且必须是大于0的数字' );
		}

		if (!isset($arg_array['codeNum']) || !$commHandler->isInteger($arg_array['codeNum'], 1)) {
			return array( 'code' => 400, 'message' => '发放数目不能为空且必须是大于0的整数' );
		}


		try{
			$coupon = new entity('mall_coupon');
			$coupon->couponID = $arg_array['couponID'];
			if($this->dbca->fetch($coupon)){
				$coupon->creator = $arg_array['creator'];
				$coupon->couponName = $arg_array['couponName'];
				$coupon->startDate = $arg_array['startDate'];
				$coupon->endDate = $arg_array['endDate'];
				$coupon->couponType = $arg_array['couponType'];
				$coupon->amount = $arg_array['amount'];
				$coupon->limitMoney = $arg_array['limitMoney'];
				$coupon->codeNum = $arg_array['codeNum'];
				$coupon->validity = $arg_array['validity'];
				$coupon->description = $arg_array['description'];
				$this->dbca->save($coupon);

				if($arg_array['couponMt'] == 2){
					$this->dbca->stmt_query('DELETE FROM mall_coupon_merchant WHERE couponID=? ','i',$arg_array['couponID']);
				}

				return array('code'=> 200,'message'=>'优惠劵保存成功');
			}else{
				return array('code'=> 400,'message'=>'没有该优惠劵');
			}
		}catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}

	/**
     * 保存门店优惠劵
     * @param $arg_array
     * @return array|null
     * $arg_array = array(
            [couponName] => 优惠券名称
            [couponID] => 优惠券ID
            [startDate] => 起始日期
            [endDate] => 结束日期
            [couponType] => 优惠券发放对象
            [limitMoney] => 礼品券使用限额
            [amount] => 优惠券金额
            [codeNum] => 发放数目
            [validity] => 有效期
            [description] => 优惠券描述
            [mallID] => 门店ID
            [creator] => 创建人
            [mallName] => 门店名称
     * )
     */
	public function saveCoupon(&$arg_array){
		//实例化公共类
		$commHandler = new commHandler();

		if (!isset($arg_array['couponName']) || empty($arg_array['couponName'])) {
			return array( 'code' => 400, 'message' => '优惠券名不能为空' );
		}

		if(!isset($arg_array['startDate']) || empty($arg_array['startDate'])){
			return array( 'code' => 400, 'message' => '优惠券使用开始日期不能为空' );
		}

		if(!isset($arg_array['endDate']) || empty($arg_array['endDate'])){
			return array( 'code' => 400, 'message' => '优惠券使用结束日期不能为空' );
		}

		if ($arg_array['startDate'] > $arg_array['endDate']) {
			return array( 'code' => 400, 'message' => '开始日期不能大于结束日期' );
		}

		if (!isset($arg_array['couponType']) || !in_array($arg_array['couponType'], array(1, 2))) {
			return array( 'code' => 400, 'message' => '请选择优惠券发放方式' );
		}

		if (!isset($arg_array['limitMoney']) || !$commHandler->isMoney($arg_array['limitMoney']) || $arg_array['limitMoney'] < 0) {
			return array( 'code' => 400, 'message' => '订单限额不能为空且必须是大于等于0的数字' );
		}

		if (!isset($arg_array['amount']) || !$commHandler->isMoney($arg_array['amount']) || $arg_array['amount'] <= 0) {
			return array( 'code' => 400, 'message' => '优惠券抵扣金额不能为空且必须是大于0的数字' );
		}

		if (!isset($arg_array['codeNum']) || !$commHandler->isInteger($arg_array['codeNum'], 1)) {
			return array( 'code' => 400, 'message' => '发放数目不能为空且必须是大于0的整数' );
		}


		try{

			$coupon = new entity('mall_coupon');
			$coupon->creator = $arg_array['creator'];
			$coupon->mallID = $arg_array['mallID'];
			$coupon->mallName = $arg_array['mallName'];
			$coupon->creator = $arg_array['creator'];
			$coupon->couponName = $arg_array['couponName'];
			$coupon->startDate = $arg_array['startDate'];
			$coupon->endDate = $arg_array['endDate'];
			$coupon->couponType = $arg_array['couponType'];
			$coupon->amount = $arg_array['amount'];
			$coupon->limitMoney = $arg_array['limitMoney'];
			$coupon->codeNum = $arg_array['codeNum'];
			$coupon->validity = $arg_array['validity'];
			$coupon->description = $arg_array['description'];
			$coupon->coupon_status = 0;
			$this->dbca->save($coupon);
			return array('code'=> 200,'message'=>'优惠劵保存成功');


		}catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}
	}

	/**
     * 查询优惠券编号信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return array|null
     */
	public function searchCouponCode( &$arg_array ) {

		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

		//优惠券编号
		if (isset($arg_array['code']) && !empty($arg_array['code'])) {
			$sql .= ' AND code = ?';
			$params_type .= 's';
			$params_array[] = $arg_array['code'];
		}

		//优惠券ID
		if (isset($arg_array['couponID']) && is_numeric($arg_array['couponID'])) {
			$sql .= ' AND couponID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['couponID'];
		}

		//会员号
		if (isset($arg_array['custID']) && !empty($arg_array['custID'])) {
			$sql .= ' AND custID = ?';
			$params_type .= 's';
			$params_array[] = trim($arg_array['custID']);
		}

		//订单号
		if (isset($arg_array['billNo']) && !empty($arg_array['billNo'])) {
			$sql .= ' AND billNo = ?';
			$params_type .= 's';
			$params_array[] = trim($arg_array['billNo']);
		}

		//是否使用
		if (isset($arg_array['used']) && in_array($arg_array['used'], array(1, 2))) {
			if ($arg_array['used'] == 1) {
				$sql .= ' AND useTime IS NULL';
			} else if ($arg_array['used'] == 2) {
				$sql .= ' AND useTime IS NOT NULL';
			}
		}



		if ($sql) {
			$sql = ' WHERE ' . substr($sql, 4);
		}

		try {

			if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

				//统计数量
				$search_sql = 'SELECT COUNT(*) AS item_count FROM mall_coupon_code ' . $sql;
				$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				$item_count = $count_array[0]->item_count;
				if ($item_count == 0) {
					$arg_array['count'] = 0;
					return null;
				}

				$arg_array['count'] = $item_count;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

				//分页
				if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				$arg_array['page'] = 1;

				$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

			} else {

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

			}

			//查询备注信息
			$search_sql = 'SELECT * FROM mall_coupon_code ' . $sql;
			$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
			if (!$temp_item_array)
			return null;

			if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'createTime'=> $item->createTime,
                        'code' => $item->code,
                        'couponID' => $item->couponID,
                        'custID' => $item->custID,
                        'billNo' => $item->billNo,
                        'useTime' => $item->useTime,
                        'useAmount' => $item->useAmount,
                        'billAmount' => $item->billAmount,
                        'merchantID' => $item->merchantID,
                        'merchantName' => $item->merchantName
                    );
                }
			}
			return $item_array;

		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}

	/**
     * 商户优惠劵商户列表
     * @param $arg_array
     * $arg_array = array(
     *      'sortname' => string 排序字段
     *      'sortorder' => string 排序方式
     *
     *      'couponID' =>优惠劵ID
     * )
     * @return array|null
     */
	public function merchantCouponList(&$arg_array){
		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

		//优惠券ID
		if( isset($arg_array['couponID']) && is_numeric($arg_array['couponID'])){
			$sql .= ' AND mcm.couponID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['couponID'];
		}

		if ($sql) {
			$sql = ' WHERE ' . substr($sql, 4);
		}


		try {

			if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

				//统计数量
				$search_sql = 'SELECT COUNT(*) AS item_count FROM mall_coupon_merchant mcm left join mall_merchant_master mmm on  mcm.merchantID = mmm.merchantID ' . $sql;
				$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				$item_count = $count_array[0]->item_count;
				if ($item_count == 0) {
					$arg_array['count'] = 0;
					return null;
				}

				$arg_array['count'] = $item_count;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

				//分页
				if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				$arg_array['page'] = 1;

				$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

			} else {

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

			}

			//查询备注信息
			$search_sql = 'SELECT * FROM mall_coupon_merchant mcm left join mall_merchant_master mmm on  mcm.merchantID = mmm.merchantID ' . $sql;
			$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
			if (!$temp_item_array)
			return null;

			if ($temp_item_array) {
				foreach ($temp_item_array as &$item) {
					$item_array[] = array(
					'merchantID' => $item->merchantID,                //商户ID
					'merchantName' => $item->merchantName,          //商户名称
					'couponID' => $item->couponID,
					'buildingName' => $item->buildingName,
					'floor' => $item->floor,
					'bigCategoryName' => $item->bigCategoryName,
					'midCategoryName' => $item->midCategoryName
					);
				}
			}

			return $item_array;

		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}
	}

	/**
     * 编辑商户优惠劵
     * @param $arg_array
     * $arg_array = array(
     *      [dt] => Array(
                [couponName] => 优惠劵名称
                [couponID] => 优惠劵ID
                [startDate] => 开始日期
                [endDate] => 结束日期
                [couponType] => 优惠劵类型
                [limitMoney] => 礼品券使用限额
                [amount] => 优惠券金额
                [codeNum] => 发放数目
                [validity] => 有效期
                [description] => 优惠券描述
                )

            [datacache] => Array(//商户ID
            )

            [creator] => 创建人
            [mallID] => 门店ID
            [mallName] => 门店名称
     * )
     * @return array|null
     */
	public function editMerchantCoupon(&$arg_array){

		if(!isset($arg_array['dt']['couponID']) || empty($arg_array['dt']['couponID']))
		return array( 'code' => 400, 'message' => '参数传递错误' );

		//实例化公共类
		$commHandler = new commHandler();

		if (!isset($arg_array['dt']['couponName']) || empty($arg_array['dt']['couponName'])) {
			return array( 'code' => 400, 'message' => '优惠券名不能为空' );
		}

		if(!isset($arg_array['dt']['startDate']) || empty($arg_array['dt']['startDate'])){
			return array( 'code' => 400, 'message' => '优惠券使用开始日期不能为空' );
		}

		if(!isset($arg_array['dt']['endDate']) || empty($arg_array['dt']['endDate'])){
			return array( 'code' => 400, 'message' => '优惠券使用结束日期不能为空' );
		}

		if ($arg_array['dt']['startDate'] > $arg_array['dt']['endDate']) {
			return array( 'code' => 400, 'message' => '开始日期不能大于结束日期' );
		}

		if (!isset($arg_array['dt']['couponType']) || !in_array($arg_array['dt']['couponType'], array(1, 2))) {
			return array( 'code' => 400, 'message' => '请选择优惠券发放方式' );
		}

		if (!isset($arg_array['dt']['limitMoney']) || !$commHandler->isMoney($arg_array['dt']['limitMoney']) || $arg_array['dt']['limitMoney'] < 0) {
			return array( 'code' => 400, 'message' => '订单限额不能为空且必须是大于等于0的数字' );
		}

		if (!isset($arg_array['dt']['amount']) || !$commHandler->isMoney($arg_array['dt']['amount']) || $arg_array['dt']['amount'] <= 0) {
			return array( 'code' => 400, 'message' => '优惠券抵扣金额不能为空且必须是大于0的数字' );
		}

		if (!isset($arg_array['dt']['codeNum']) || !$commHandler->isInteger($arg_array['dt']['codeNum'], 1)) {
			return array( 'code' => 400, 'message' => '发放数目不能为空且必须是大于0的整数' );
		}


		try{
			$coupon = new entity('mall_coupon');
			$coupon->couponID = $arg_array['dt']['couponID'];
			if($this->dbca->fetch($coupon)){
				$coupon->creator = $arg_array['creator'];
				$coupon->couponName = $arg_array['dt']['couponName'];
				$coupon->startDate = $arg_array['dt']['startDate'];
				$coupon->endDate = $arg_array['dt']['endDate'];
				$coupon->couponType = $arg_array['dt']['couponType'];
				$coupon->amount = $arg_array['dt']['amount'];
				$coupon->limitMoney = $arg_array['dt']['limitMoney'];
				$coupon->codeNum = $arg_array['dt']['codeNum'];
				$coupon->validity = $arg_array['dt']['validity'];
				$coupon->description = $arg_array['dt']['description'];
				$this->dbca->save($coupon);
				//删除优惠券对应的商户
				$this->dbca->stmt_query('DELETE FROM mall_coupon_merchant where couponID = ?','i',$arg_array['dt']['couponID']);

				if(isset($arg_array['datacache'])){
					foreach($arg_array['datacache'] as $val){
						if($val){
							$couponMerchant = new entity('mall_coupon_merchant');
							$couponMerchant->creator = $arg_array['creator'];
							$couponMerchant->couponID = $arg_array['dt']['couponID'];
							$couponMerchant->merchantID = $val;
							$this->dbca->save($couponMerchant);
						}
					}
				}

				return array('code'=> 200,'message'=>'优惠劵保存成功');
			}else{
				return array('code'=> 400,'message'=>'没有该优惠劵');
			}
		}catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}
	}

	/**
     * 保存商户优惠劵
     * @param $arg_array
     * $arg_array = array(
     *      [dt] => Array(
                [couponName] => 优惠劵名称
                [startDate] => 开始日期
                [endDate] => 结束日期
                [couponType] => 优惠劵类型
                [limitMoney] => 礼品券使用限额
                [amount] => 优惠券金额
                [codeNum] => 发放数目
                [validity] => 有效期
                [description] => 优惠券描述
            )

            [datacache] => Array(//商户ID
            )

            [creator] => 创建人
            [mallID] => 门店ID
            [mallName] => 门店名称
     * )
     * @return array|null
     */
	public function saveMerchantCoupon(&$arg_array){
		//实例化公共类
		$commHandler = new commHandler();

		if (!isset($arg_array['dt']['couponName']) || empty($arg_array['dt']['couponName'])) {
			return array( 'code' => 400, 'message' => '优惠券名不能为空' );
		}

		if(!isset($arg_array['dt']['startDate']) || empty($arg_array['dt']['startDate'])){
			return array( 'code' => 400, 'message' => '优惠券使用开始日期不能为空' );
		}

		if(!isset($arg_array['dt']['endDate']) || empty($arg_array['dt']['endDate'])){
			return array( 'code' => 400, 'message' => '优惠券使用结束日期不能为空' );
		}

		if ($arg_array['dt']['startDate'] > $arg_array['dt']['endDate']) {
			return array( 'code' => 400, 'message' => '开始日期不能大于结束日期' );
		}

		if (!isset($arg_array['dt']['couponType']) || !in_array($arg_array['dt']['couponType'], array(1, 2))) {
			return array( 'code' => 400, 'message' => '请选择优惠券发放方式' );
		}

		if (!isset($arg_array['dt']['limitMoney']) || !$commHandler->isMoney($arg_array['dt']['limitMoney']) || $arg_array['dt']['limitMoney'] < 0) {
			return array( 'code' => 400, 'message' => '订单限额不能为空且必须是大于等于0的数字' );
		}

		if (!isset($arg_array['dt']['amount']) || !$commHandler->isMoney($arg_array['dt']['amount']) || $arg_array['dt']['amount'] <= 0) {
			return array( 'code' => 400, 'message' => '优惠券抵扣金额不能为空且必须是大于0的数字' );
		}

		if (!isset($arg_array['dt']['codeNum']) || !$commHandler->isInteger($arg_array['dt']['codeNum'], 1)) {
			return array( 'code' => 400, 'message' => '发放数目不能为空且必须是大于0的整数' );
		}


		try{
			$coupon = new entity('mall_coupon');
			$coupon->creator = $arg_array['creator'];
			$coupon->mallID = $arg_array['mallID'];
			$coupon->mallName = $arg_array['mallName'];
			$coupon->couponName = $arg_array['dt']['couponName'];
			$coupon->startDate = $arg_array['dt']['startDate'];
			$coupon->endDate = $arg_array['dt']['endDate'];
			$coupon->couponType = $arg_array['dt']['couponType'];
			$coupon->amount = $arg_array['dt']['amount'];
			$coupon->limitMoney = $arg_array['dt']['limitMoney'];
			$coupon->codeNum = $arg_array['dt']['codeNum'];
			$coupon->validity = $arg_array['dt']['validity'];
			$coupon->description = $arg_array['dt']['description'];
			$this->dbca->save($coupon);

			$insert_id = $this->dbca->insert_id;

			if(isset($arg_array['datacache'])){
				foreach($arg_array['datacache'] as $val){
					if($val){
						$couponMerchant = new entity('mall_coupon_merchant');
						$couponMerchant->creator = $arg_array['creator'];
						$couponMerchant->couponID = $insert_id;
						$couponMerchant->merchantID = $val;
						$this->dbca->save($couponMerchant);
					}
				}
			}

			return array('code'=> 200,'message'=>'优惠劵保存成功');

		}catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}

	/**
     * 根据门店编号查询门店大分类中分类信息
     * @param	array	$params		请求参数数组
     * 			int		$params['mallID']	门店ID
     */
	public function getMallCategoryInfo($arg_array){
		if (!isset($arg_array['mallID']) || empty($arg_array['mallID'])) {
			return array('code'=>400,'message'=>'门店信息有误');
		}

		$sql_get_category_info = 'SELECT map.mallID,mall.mallName,map.bigCategoryID,bigCate.bigCategoryName,map.midCategoryID,midCate.midCategoryName
								FROM mall_category_map map 
								INNER JOIN mall_master mall ON map.mallID=mall.mallID 
								INNER JOIN mall_bigCategory bigCate ON map.bigCategoryID=bigCate.bigCategoryID 
								INNER JOIN mall_midCategory midCate ON map.midCategoryID=midCate.midCategoryID 
								WHERE map.mallID=? AND mall.useFlg=1 AND bigCate.useFlg=1 AND midCate.useFlg=1 ORDER BY bigCate.sortorder ASC,midCate.sortorder ASC';
		$category_result = $this->dbca->stmt_query($sql_get_category_info,'i',$arg_array['mallID']);
		if (!$category_result) {
			return array('code'=>400,'message'=>'门店分类信息未找到');
		}

		$return_category_arr = array(
		'mallID'	=> $category_result[0]->mallID,
		'mallName'	=> $category_result[0]->mallName
		);
		foreach ($category_result as $category_obj){
			if (!isset($return_category_arr['category'][$category_obj->bigCategoryID])) {
				$return_category_arr['category'][$category_obj->bigCategoryID] = array(
				'bigCateID'		=> $category_obj->bigCategoryID,
				'bigCateName'	=> $category_obj->bigCategoryName,
				'midCate'		=> array()
				);
			}

			if (!isset($return_category_arr['category'][$category_obj->bigCategoryID]['midCate'][$category_obj->midCategoryID])) {
				$return_category_arr['category'][$category_obj->bigCategoryID]['midCate'][$category_obj->midCategoryID] = array(
				'midCateID'		=> $category_obj->midCategoryID,
				'midCateName'	=> $category_obj->midCategoryName
				);
			}
		}

		return array('code'=>200,'message'=>'ok','data'=>$return_category_arr);
	}

	/**
	 * 查询门店的问卷调查
	 */
	public function searchVoteInfo(&$arg_array) {
		
		//sql字符串
		$sql = '';

		//参数类型字符串
		$param_type = '';

		//参数值数组
		$param_data = array();

		if(isset($arg_array['mallID']) && $arg_array['mallID'] > 0){
			$sql .= ' AND mallID = ?';
			$param_type .= 'i';
			$param_data[] = $arg_array['mallID'];
		}

		if(isset($arg_array['questionID']) && $arg_array['questionID'] > 0){
			$sql .= ' AND questionID = ?';
			$param_type .= 'i';
			$param_data[] = $arg_array['questionID'];
		}

		if(isset($arg_array['current_date']) && $arg_array['current_date'] > 0){
			$sql .= ' AND startDate <= ? AND endDate >= ?';
			$param_type .='ss';
			$param_data[] = $arg_array['current_date'];
			$param_data[] = $arg_array['current_date'];
		}

		if(isset($arg_array['useFlg']) && in_array($arg_array['useFlg'] , array(0,1) ) ){
			$sql .= ' AND useFlg = ?';
			$param_type .= 'i';
			$param_data[] = $arg_array['useFlg'];
		}

        if(isset($arg_array['questionStatus']) &&  in_array($arg_array['questionStatus'] , array(0,1) ) ){
            $sql .= ' AND questionStatus = ?';
            $param_type .= 'i';
            $param_data[] = $arg_array['questionStatus'];
        }

		if($sql){
			$sql = 'WHERE '.substr($sql,4);

		}

		try{
			if(isset($arg_array['rp']) && $arg_array['rp'] >1){

				$searchStr = 'SELECT COUNT(*) AS item_count FROM mall_questionnaire '.$sql;

				$count_array = $this->dbca->stmt_query($searchStr,$param_type,$param_data);

				$count = $count_array[0]->item_count;
				if($count == 0){
					$arg_array['count'] = 0;
					return null;
				}
				$arg_array['count'] = $count;

				if(isset($arg_array['sortname']) && !empty($arg_array['sortname'])){
					$sql .= sprintf(' ORDER BY %s %s',$arg_array['sortname'],$arg_array['sortorder']);
				}
				//分页
				if(isset($arg_array['page']) && $arg_array['page'] > 0){
					$sql .= sprintf(' LIMIT %d, %d',($arg_array['page']-1)*$arg_array['rp'],$arg_array['rp']);
				}

			}else{
				$arg_array['count'] = 0;
				//排序
				if(isset($arg_array['sortname']) && !empty($arg_array['sortname'])){
					$sql .= sprintf(' ORDER BY %s %s',$arg_array['sortname'],$arg_array['sortorder']);
				}
			}

			//查询信息
			$search_sql = 'SELECT * FROM mall_questionnaire ' . $sql;

			$temp_item_array = &$this->dbca->stmt_query($search_sql, $param_type, $param_data);

			if ($temp_item_array){

				foreach($temp_item_array as &$item) {

					$item_array[] = array(
					'uuid' => $item->uuid,
					'createTime' => $item->createTime,
					'mallID' =>$item->mallID,
					'questionID' => $item->questionID,
					'questionName' =>$item->questionName,
					'startDate'   =>$item->startDate,
					'endDate'    =>$item->endDate,
					'questionnaireNum' => $item->questionnaireNum,
					'questionStatus'   => $item->questionStatus,
					'useFlg' => $item->useFlg
					);
				}

				return $item_array;
			}

		}catch(Exception $e){

			error_log($e->getMessage());
			return null;
		}

	}

	/**
	 * 根据问卷调查ID 查找出投票项
	 */
	public function searchVote(&$arg_array) {

		if(!isset($arg_array['questionID'])|| $arg_array['questionID'] <= 0){
			return null;
		}
		$result = $this->dbca->stmt_query('SELECT * FROM mall_questionnaire_vote WHERE questionID = ?','i',$arg_array['questionID']);
		if($result){
			foreach($result as &$vote){
				$result_array[] = array(
					'questionID' => $vote->questionID,
					'voteID'     => $vote->voteID,
					'voteName'   => $vote->voteName,
					'canMulti'   => $vote->canMulti,
					'isMust'     => $vote->isMust,
					'voteNum'    => $vote->voteNum
				);
			}
			return $result_array;
		} else {
			return null;
		}
	}

	/**
	 * 根据投票ID找出选项
	 */

	public function searchOptions(&$arg_array){
		if(!isset($arg_array['voteID']) || $arg_array['voteID'] <=0){
			return array('code' => 400,'message' => '参数错误');
		}
		$result = $this->dbca->stmt_query('SELECT * FROM mall_questionnaire_vote_option WHERE voteID = ?','i',$arg_array['voteID']);
		if($result){
			foreach ($result as $k){
				$result_array[] = array(
				'optionName' =>$k->optionName,
				'optionSortby' =>$k->optionSortby,
				'optionNum'    =>$k->optionNum
				);
			}
			return $result_array;
		}

	}

	/**
	 * 问卷调查保存
	 */
	public function saveQuestionnaireInfo(&$arg_array) {
	
		if(!isset($arg_array['mallID'],$arg_array['creator'],$arg_array['questionName'],$arg_array['startDate'],$arg_array['endDate'],$arg_array['useFlg'],$arg_array['vote'])){
			return array('code' => 400,'message' => '参数错误');
		}

		if(empty($arg_array['mallID']) || !is_numeric($arg_array['mallID'])){
			return array('code' => 400, 'message' => '门店号不存在,请仔细检查');
		}

		if(empty($arg_array['questionName'])){
			return array('code' => 400, 'message' => '问卷调查名称不能为空');
		}

		if(empty($arg_array['startDate'])){
			return array('code' => 400, 'message' => '开始日期不能为空');
		}

		if(empty($arg_array['endDate'])){
			return array('code' => 400, 'message' => '结束日期不能为空');
		}
		
		if($arg_array['startDate'] > $arg_array['endDate']){
			return array('code' => 400, 'message' => '开始日期不能大于结束日期');
		}
	
		if(!in_array($arg_array['useFlg'], array(0, 1))){
			$arg_array['useFlg'] = 1;
		}
		
		if (count($arg_array['vote']) == 0) {
			return array('code' => 400, 'message' => '没有投票主题');
		}
		
		$questionID = 0;
		
		try{

			//开始事务
			$this->dbca->beginTransaction();
			
			$mall_questionnaire = new entity('mall_questionnaire');
			if(!empty($arg_array['questionID'])) {
				
				//查询问卷信息
				$mall_questionnaire->questionID = $arg_array['questionID'];
				if(!$this->dbca->fetch($mall_questionnaire)){
					throw new Exception('问卷调查信息没有找到', 404);
				}
				
				//检查问卷调查状态
				if ($mall_questionnaire->questionStatus == 1) {
					throw new Exception('问卷调查已审核，无法修改', 404);
				}
				
				$questionID = $mall_questionnaire->questionID;
				
				//删除投票主题
				$delete_sql = 'DELETE FROM mall_questionnaire_vote WHERE questionID = ?';
				$this->dbca->stmt_query($delete_sql, 'i', $questionID);
				
				//删除投票选项
				$delete_sql = 'DELETE FROM mall_questionnaire_vote_option WHERE questionID = ?';
				$this->dbca->stmt_query($delete_sql, 'i', $questionID);
				
			} else {
				$mall_questionnaire->creator = $arg_array['creator'];
				$mall_questionnaire->mallID = $arg_array['mallID'];
			}

			//保存或更新问卷主表信息
			$mall_questionnaire->questionName = $arg_array['questionName'];
			$mall_questionnaire->startDate = $arg_array['startDate'];
			$mall_questionnaire->endDate = $arg_array['endDate'];
			$mall_questionnaire->useFlg = $arg_array['useFlg'];
			$mall_questionnaire->questionStatus = 0;
			$result = $this->dbca->save($mall_questionnaire);
			if ($result) {
				if ($questionID == 0) {
					$questionID = $this->dbca->insert_id;
				}
			} else {
				
				throw new Exception('问卷信息保存失败，请重试或联系系统管理员', 404);
				
			}
			
			//保存投票主题和选项
			foreach($arg_array['vote'] as $key => &$vote) {
				
				$key += 1;
				
				//检查投票信息
				if (!isset($vote['voteName']) || empty($vote['voteName'])) {
					throw new Exception(sprintf('"投票主题%d"，主题名不能为空', $key), 400);
				}
				if (!isset($vote['canMulti']) || !in_array($vote['canMulti'], array(0, 1))) {
					throw new Exception(sprintf('"投票主题%d"，请选择是否可以多选', $key), 400);
				}
				if (!isset($vote['isMust']) || !in_array($vote['isMust'], array(0, 1))) {
					throw new Exception(sprintf('"投票主题%d"，请选择是否是否必选', $key), 400);
				}
				if (!isset($vote['option']) || !is_array($vote['option']) || count($vote['option']) == 0) {
					throw new Exception(sprintf('"投票主题%d"，选项不能为空', $key), 400);
				}
				
				//保存投票主题信息
				$mall_questionnaire_vote = new entity('mall_questionnaire_vote');
				$mall_questionnaire_vote->creator = $mall_questionnaire->creator;
				$mall_questionnaire_vote->questionID = $questionID;
				$mall_questionnaire_vote->voteName = $vote['voteName'];
				$mall_questionnaire_vote->canMulti = $vote['canMulti'];
				$mall_questionnaire_vote->isMust = $vote['isMust'];
				$mall_questionnaire_vote->voteNum = 0;
				$this->dbca->save($mall_questionnaire_vote);
				$voteID = $this->dbca->insert_id;
				
				//保存投票选项信息
				$option_num = 0;
				foreach ($vote['option'] as &$option) {
					
					if (empty($option)) {
						continue;
					}
					
					$option_num++;
					//实例化
					$mall_questionnaire_vote_option = new entity('mall_questionnaire_vote_option');
					$mall_questionnaire_vote_option->creator = $mall_questionnaire->creator;
					$mall_questionnaire_vote_option->questionID = $questionID;
					$mall_questionnaire_vote_option->voteID = $voteID;
					$mall_questionnaire_vote_option->optionName = $option;
					$mall_questionnaire_vote_option->optionNum = 0;
					$mall_questionnaire_vote_option->optionSortby = $option_num;
					$this->dbca->save($mall_questionnaire_vote_option);
					
				}
				
				if ($option_num == 0) {
					throw new Exception(sprintf('"投票主题%d"，选项不能为空', $key), 400);
				}
				
			}

			$this->dbca->commit();
			
			return array('code' => 200,'message' => '保存成功');
			
		}catch(Exception $e){
			$this->dbca->rollback();
			if ($e->getCode() > 0) {
				return array('code' => $e->getCode(),'message' => $e->getMessage());
			} else {
				error_log($e->getMessage());
				return array('code' => 500,'message' => '系统错误');
			}
			
		}


	}

	/**
     * 修改问卷调查使用状态
     * $arg_array = array(
     * 		id => useFlg
     * )
     */
	public function voteChangeStatus($arg_array) {

		//参数检查
		if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '') {
			return array( 'code' => 400, 'message' => '缺少参数' );
		}


		$str_array = explode('_', $arg_array['useFlg_str']);

		try{
			//检查问卷调查是否存在或已经被操作
			$mall_questionnaire = new entity('mall_questionnaire');
			$mall_questionnaire->questionID = $str_array[0] ;
			if (!$this->dbca->fetch( $mall_questionnaire )){
				throw new Exception(sprintf('问卷调查号「%d」,的问卷调查不存在,请审核后再操作',$str_array[0]) , 400) ;
			}

			//检查问卷调查状态是否已经被修改
			if($mall_questionnaire->useFlg == $str_array[1] && $str_array[1] == 1){
				throw new Exception(sprintf('问卷调查号「%d」,的问卷调查已启用',$str_array[0]) , 400) ;
			}

			if($mall_questionnaire->useFlg == $str_array[1] && $str_array[1] == 0){
				throw new Exception(sprintf('问卷调查号「%d」,的问卷调查已禁用',$str_array[0]) , 400) ;
			}

			//保存
			$mall_questionnaire->useFlg = $str_array[1] ;
			$this->dbca->save( $mall_questionnaire , 'mall_questionnaire' );

		}catch (Exception $e) {
			if ($e->getCode() > 0){
				return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
			}else {
				error_log($e->getMessage());
				return array( 'code' => 500, 'message' => '系统错误' );
			}
		}

		if($str_array[1] == 1){
			return array( 'code' => 200, 'message' => '问卷调查启用成功' );
		}else if ($str_array[1] == 0){
			return array( 'code' => 200, 'message' => '问卷调查禁用成功' );
		}
	}

	/**
     * 审核问卷调查状态
     * $arg_array = array(
     * 		id => useFlg
     * )
     */
	public function voteCheckStatus($arg_array) {

		//参数检查
		if (!isset($arg_array['status_str']) || $arg_array['status_str'] == '') {
			return array( 'code' => 400, 'message' => '缺少参数' );
		}


		$str_array = explode('_', $arg_array['status_str']);

		try{
			//检查商户是否存在或已经被操作
			$mall_questionnaire = new entity('mall_questionnaire');
			$mall_questionnaire->questionID = $str_array[0] ;
			if (!$this->dbca->fetch( $mall_questionnaire )){
				throw new Exception(sprintf('问卷调查号「%d」,的问卷调查不存在,请审核后再操作',$str_array[0]) , 400) ;
			}

			//检查商户状态是否已经被修改
			if($mall_questionnaire->questionStatus == $str_array[1] && $str_array[1] == 1){
				throw new Exception(sprintf('问卷调查号「%d」,的问卷调查已审核',$str_array[0]) , 400) ;
			}

			//保存
			$mall_questionnaire->questionStatus = 1 ;
			$this->dbca->save( $mall_questionnaire , 'mall_questionnaire' );

		}catch (Exception $e) {
			if ($e->getCode() > 0){
				return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
			}else {
				error_log($e->getMessage());
				return array( 'code' => 500, 'message' => '系统错误' );
			}
		}

		if($str_array[1] == 0){
			return array( 'code' => 200, 'message' => '问卷调查审核成功' );
		}
	}
	
	/**
	 * 删除问卷调查
	 */
	public function deletevote($arg_array) {

		try{
			//开启问卷调查
			$this->dbca->beginTransaction();
			foreach($arg_array as $k){
				$mall_questionnaire = new entity('mall_questionnaire');
				$mall_questionnaire->questionID = $k;
			if($this->dbca->fetch($mall_questionnaire)){
				$this->dbca->delete($mall_questionnaire,'mall_questionnaire');
			}	
				
			}
			$this->dbca->commit();
			return array( 'code' => 200, 'message' => '删除成功' );

		}catch(Exception $e){
			$this->dbca->rollBack();
			error_log($e->getMessage());
		}
	}

	/**
     * 商户对应商户优惠劵列表
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     *
     *      'merchantID' => 商户ID
     *
     * )
     * @param $arg_array
     * @return array|null
     */
	public function searchMerchantCoupon(&$arg_array){

		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

		//所属门店的ID
		if(isset($arg_array['mallID'])&&!empty($arg_array['mallID'])){
			$sql .= ' AND mc.mallID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['mallID'];
		}

		//优惠券ID
		if (isset($arg_array['couponID']) && is_numeric($arg_array['couponID'])) {
			$sql .= ' AND mc.couponID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['couponID'];
		}

		//优惠券名称
		if(isset($arg_array['couponName']) && !empty($arg_array['couponName']) ){
			$sql .= ' AND mc.couponName LIKE ? ';
			$params_type .= 's';
			$params_array[] = '%' . trim($arg_array['couponName']) . '%';
		}

		//开始日期
		if(isset($arg_array['startDate']) && !empty($arg_array['startDate']) ){
			$sql .= ' AND mc.startDate <= ? ';
			$params_type .= 's';
			$params_array[] = $arg_array['startDate'];
		}

		//结束日期
		if(isset($arg_array['endDate']) && !empty($arg_array['endDate']) ){
			$sql .= ' AND mc.endDate >= ? ';
			$params_type .= 's';
			$params_array[] = $arg_array['endDate'];
		}

		//优惠券发放方式
		if(isset($arg_array['couponType']) && in_array($arg_array['couponType'],array(1,2))){
			$sql .= ' AND mc.couponType = ? ';
			$params_type .= 'i';
			$params_array[] = $arg_array['couponType'];
		}

		//优惠券发放方式
		if(isset($arg_array['couponType']) && in_array($arg_array['couponType'],array(1,2))){
			$sql .= ' AND mc.couponType = ? ';
			$params_type .= 'i';
			$params_array[] = $arg_array['couponType'];
		}

		//商户ID
		if(isset($arg_array['merchantID']) && in_array($arg_array['merchantID'],array(1,2))){
			$sql .= ' AND mcm.merchantID = ? ';
			$params_type .= 'i';
			$params_array[] = $arg_array['merchantID'];
		}

		if ($sql) {
			$sql = ' WHERE ' . substr($sql, 4) .' GROUP BY mcm.couponID  ';
		}


		try {

			if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

				//统计数量
				$search_sql = 'SELECT COUNT(*) AS item_count FROM mall_coupon_merchant mcm LEFT JOIN mall_coupon mc ON mcm.couponID = mc.couponID  ' . $sql;
				$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				$item_count = $count_array[0]->item_count;
				if ($item_count == 0) {
					$arg_array['count'] = 0;
					return null;
				}

				$arg_array['count'] = $item_count;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

				//分页
				if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				$arg_array['page'] = 1;

				$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

			} else {

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

			}

			//查询备注信息
			$search_sql = 'SELECT * FROM mall_coupon_merchant mcm LEFT JOIN mall_coupon mc ON mcm.couponID = mc.couponID ' . $sql;
			$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

			if (!$temp_item_array)
			return null;

			if ($temp_item_array) {
				foreach ($temp_item_array as &$item) {
					if ($item->couponType == 1)
					$type_name = '门店优惠券';
					else if ($item->couponType == 2)
					$type_name = '商户优惠券';
					$item_array[] = array(
					'mallID' => $item->mallID,                //门店ID
					'mallName' => $item->mallName,            //门店名称
					'couponID' => $item->couponID,            //ID
					'couponName' => $item->couponName,        //名称
					'startDate' => $item->startDate,          //开始日期
					'endDate' => $item->endDate,              //结束日期
					'couponType' => $item->couponType,        //发放方式
					'amount' => $item->amount,                //优惠券金额
					'limitMoney' => $item->limitMoney,        //订单使用限额
					'codeNum' => $item->codeNum,            //发放数量
					'validity' => $item->validity,            //有效期
					'description' => $item->description,      //描述
					'coupon_status' => $item->coupon_status,     //状态
					'type_name' => $type_name
					);
				}
			}

			return $item_array;

		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}

	/**
     * 查询最新消息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return array|null
     */
	public function searchCustMessage( &$arg_array ) {

		//sql字符串
		$sql = '';

		//参数类型字符串
		$params_type = '';

		//参数值数组
		$params_array = array();

		//会员ID
		if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
			$sql .= ' AND pcustID = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['pcustID'];
		}

		//会员号
		if (isset($arg_array['title']) && !empty($arg_array['title'])) {
			$sql .= ' AND title = ?';
			$params_type .= 's';
			$params_array[] = trim($arg_array['title']);
		}

		//是否已读
		if (isset($arg_array['isRead']) && in_array($arg_array['isRead'], array(0,1) ) ) {
			$sql .= ' AND isRead = ?';
			$params_type .= 'i';
			$params_array[] = $arg_array['isRead'];
		}



		if ($sql) {
			$sql = ' WHERE ' . substr($sql, 4);
		}

		try {

			if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

				//统计数量
				$search_sql = 'SELECT COUNT(*) AS item_count FROM cust_message ' . $sql;
				$count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
				$item_count = $count_array[0]->item_count;
				if ($item_count == 0) {
					$arg_array['count'] = 0;
					return null;
				}

				$arg_array['count'] = $item_count;

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

				//分页
				if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
				$arg_array['page'] = 1;

				$sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

			} else {

				//排序
				if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
				$sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

			}

			//查询备注信息
			$search_sql = 'SELECT * FROM cust_message ' . $sql;
			$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
			if (!$temp_item_array)
			return null;

			if ($temp_item_array) {
				foreach ($temp_item_array as &$item) {
					$item_array[] = array(
					'uuid'=> $item->uuid,
					'timeStamp'=> $item->timeStamp,
					'creator'=> $item->creator,
					'createTime'=> $item->createTime,
					'pcustID' => $item->pcustID,
					'title' => $item->title,
					'message' => $item->message,
					'link' => $item->link,
					'isRead' => $item->isRead
					);
				}
			}
			return $item_array;

		} catch (Exception $e) {

			error_log($e->getMessage());
			return null;

		}

	}

	/**
     * 修改最新消息阅读状态
     * $uuid   uuid
     */
	function changeCustMessageStatus( $uuid ){

		if( !isset($uuid) || empty($uuid) )
		return array('code'=>400 , '参数错误');

		//查询消息
		$cust_message = new entity('cust_message');
		$cust_message->uuid = $uuid;

		if( !$this->dbca->fetch($cust_message) )
		return array('code'=>400 , '没有找到信息');

		$cust_message->isRead = 1;

		try{

			//更改状态
			$this->dbca->save($cust_message);

			return array('code'=>200 , 'ok');

		}catch(Exception $e){
			error_log($e->getMessage());
			return array('code'=>400 , '系统错误');

		}

	}

	/**
     * 取消预约
     */
	function cancelReserve( $arg_array ){

		if( !isset($arg_array['reserve_detailID'],$arg_array['pcustID']) || empty($arg_array['reserve_detailID']) || empty($arg_array['pcustID']) )
		return array('code'=>400 , 'message'=>'参数错误');

		if( !is_numeric($arg_array['reserve_detailID']) || !is_numeric($arg_array['pcustID']) )
		return array('code'=>400 , 'message'=>'参数错误');

		//查询预约信息
		$reserve_detail = new entity('mall_merchant_reserve_user_detail');
		$reserve_detail->reserve_detailID = $arg_array['reserve_detailID'];
		$reserve_detail->pcustID   = $arg_array['pcustID'];

		if( !$this->dbca->fetch($reserve_detail) )
		return array('code'=>400 , 'message'=>'没有找到信息');

		$reserve_detail->reserve_status   = 3;

		try{

			//更新状态
			$this->dbca->save($reserve_detail);

			return array('code'=>200 , 'message'=>'取消成功');

		}catch (Exception $e){
			error_log($e->getMessage());
			return array('code'=>500 , 'message'=>'系统错误，操作失败');
		}

	}

	/**
	 * 保存商户信息
	 */
	public function saveMerchantInfo(&$arg_array) {
		global $G_PGLOB;

		quanli_include('module/base/fileDirHandler.class.php');
		
		if (!isset($arg_array['merchantName'], $arg_array['mallID'], $arg_array['useFlg'], $arg_array['creator'])) {
			return array( 'code' => 400, 'message' => '参数错误' );
		}

		if(empty($arg_array['merchantName'])){
			return array( 'code' => 400, 'message' => '商户名称不能为空' );
		}

		if(empty($arg_array['mallID'])){
			return array( 'code' => 400, 'message' => '门店不能为空' );
		}

		if(empty($arg_array['buildingID'])){
			return array( 'code' => 400, 'message' => '楼宇不能为空' );
		}


		//根据1级分类id 获得分类名
		if(!empty($arg_array['bigCategoryID'])){
			$result = $this->dbca->stmt_query('SELECT bigCategoryName FROM mall_bigCategory WHERE bigCategoryID = ?','i',$arg_array['bigCategoryID']);
			$bigCategoryName = $result[0]->bigCategoryName;
		}

		if(!empty($arg_array['midCategoryID'])){
			$result = $this->dbca->stmt_query('SELECT midCategoryName FROM mall_midCategory WHERE midCategoryID = ?','i',$arg_array['midCategoryID']);
			$midCategoryName = $result[0]->midCategoryName;
		}

		if(!empty($arg_array['buildingID'])){
			$result = $this->dbca->stmt_query('SELECT buildingName FROM mall_building WHERE buildingID = ?','i',$arg_array['buildingID']);
			$buildingName = $result[0]->buildingName;
		}


		try {

			//查询门店信息
			$m_arg_array = array(
			'mallID' => $arg_array['mallID']
			);
			$mall_array = $this->searchMall( $m_arg_array );
			if (!$mall_array) {
				throw new Exception('门店信息没有找到', 404);
			}

			//新增或修改门店楼宇信息
			$mall_merchant_master = new entity('mall_merchant_master');
			if (!empty($arg_array['merchantID']) && $arg_array['merchantID'] > 0) {//修改
				$mall_merchant_master->merchantID = $arg_array['merchantID'];
				if (!$this->dbca->fetch($mall_merchant_master)) {
					throw new Exception('商户信息没有找到', 404);
				}
			} else {//增加

				$mall_merchant_master->creator = $arg_array['creator'];

			}

			$commHandler = new commHandler($this->dbca);
			$mall_merchant_master->merchantName = $commHandler->convertVar( $arg_array['merchantName'] );
			$mall_merchant_master->phone        = $arg_array['phone'];
			$mall_merchant_master->mobile       = $arg_array['mobile'];
			$mall_merchant_master->mallID       = $arg_array['mallID'];
			$mall_merchant_master->mallName     = $mall_array[0]['mallName'];
			$mall_merchant_master->buildingID   = $arg_array['buildingID'];
			$mall_merchant_master->buildingName = $buildingName;
			$mall_merchant_master->bigCategoryID = $arg_array['bigCategoryID'];
			$mall_merchant_master->bigCategoryName = $bigCategoryName;
			$mall_merchant_master->midCategoryID = $arg_array['midCategoryID'];
			$mall_merchant_master->midCategoryName = $midCategoryName;
			$mall_merchant_master->floor        = $arg_array['floor'];
			
			$mall_merchant_master->houseNumber  = $arg_array['houseNumber'];
			if($arg_array != ''){
				$mall_merchant_master->consumerPrice = $arg_array['consumerPrice'];
			}
			$mall_merchant_master->provinceid   = $mall_array[0]['provinceid'];
			$mall_merchant_master->provinceName = $mall_array[0]['provinceName'];
			$mall_merchant_master->cityid       = $mall_array[0]['cityid'];
			$mall_merchant_master->cityName     = $mall_array[0]['cityName'];
			$mall_merchant_master->countyid     = $mall_array[0]['countyid'];
			$mall_merchant_master->countyName   = $mall_array[0]['countyName'];
			$mall_merchant_master->address      = $mall_array[0]['address'];
			$mall_merchant_master->description  = $commHandler->convertVar($arg_array['description']);
			$mall_merchant_master->useFlg       = $arg_array['useFlg'];
			$fileDirHandler = new fileDirHandler();

				if (empty($arg_array['logo_img'])) {
					$oldName = null;
				} else {
					$oldName = G_APPLICATION_BASEPATH . $arg_array['logo_img'];
					$newName = G_IMAGE_SAVE_ROOT . 'merchant/' . $fileDirHandler->basename($oldName);
				}
				if (!empty($oldName)) {
					if (!$fileDirHandler->move($oldName, $newName)) {
						throw new Exception('文件移动失败', 404);
					}
					$mall_merchant_master->logo = 'merchant/' . $fileDirHandler->basename($oldName);
				
				}
			$this->dbca->save($mall_merchant_master,'mall_merchant');
			$merchantID = $this->dbca->insert_id;
			for($i=0;$i<count($arg_array['det_img']);$i++){
				$fileDirHandler = new fileDirHandler();

				if (empty($arg_array['det_img'][$i])) {
					$oldName = null;
				} else {
					$oldName = G_APPLICATION_BASEPATH . $arg_array['det_img'][$i];
					$newName = G_IMAGE_SAVE_ROOT . 'merchant/' . $fileDirHandler->basename($oldName);
				}
				if (!empty($oldName)) {
					if (!$fileDirHandler->move($oldName, $newName)) {
						throw new Exception('文件移动失败', 404);
					}
					$mall_merchant_pic = new entity('mall_merchant_pic');
					if($merchantID){
						$mall_merchant_pic->merchantID = $merchantID;
					}else{
						$mall_merchant_pic->merchantID = $arg_array['merchantID'];
					}
					$mall_merchant_pic->sortOrder = $i;

					$this->dbca->fetch($mall_merchant_pic);
					$mall_merchant_pic->creator = $arg_array['creator'];
					$mall_merchant_pic->pic = 'merchant/' . $fileDirHandler->basename($oldName);
					$this->dbca->save($mall_merchant_pic);
				}
			}

			return array( 'code' => 200, 'message' => '商户保存成功' );

		} catch (Exception $e) {

			if ($e->getCode() > 0) {
				return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
			} else {
				error_log($e->getMessage());
				return array( 'code' => 500, 'message' => '系统错误' );
			}

		}
	}

    /**
     * 查询商户图片
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
    'sortname' => string 排序字段
    'sortorder' => string 排序方式
    'page' => int 分页页码
    'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchMerchantPic( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //商户ID
        if ( isset($arg_array['merchantID']) && is_numeric($arg_array['merchantID']) ) {
            $sql .= ' AND merchantID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['merchantID'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM mall_merchant_pic ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询商户图片信息
            $search_sql = 'SELECT * FROM mall_merchant_pic ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'merchantID' => $item->merchantID,
                    'pic'        => $item->pic ? G_IMAGE_URL . $item->pic : '',
                    'picID'      => $item->picID,
                    'sortOrder'  => $item->sortOrder
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }

    /**
	 * 保存门店信息
	 */
	public function saveMallInfo(&$arg_array){
		
		//加载文件上传类
		quanli_include('module/base/fileDirHandler.class.php');
		
		if(!isset($arg_array['mallName']) || empty($arg_array['mallName'])){
			return array('code'=>400,'message'=>'门店名称不能为空');
		}
		
		if(!isset($arg_array['mallCode']) || empty($arg_array['mallCode'])){
			return array('code'=>400,'message'=>'门店编号不能为空');
		} else {
			//检查门店编号是否重复
			$mall_array = array(
				'mallCode' => $arg_array['mallCode']
			);
			
			$mall_request = $this->searchMall($mall_array);
			if ($mall_request) {
				if (isset($arg_array['mallID']) && !empty($arg_array['mallID']) && $arg_array['mallID'] > 0 && $mall_request[0]['mallID'] != $arg_array['mallID']) {
					return array('code' => 400, 'message' => sprintf('门店编号「%s」已经存在，请重新录入',$arg_array['mallCode']));
				} else if(!isset($arg_array['mallID']) || empty($arg_array['mallID'])) {
					return array('code' => 400, 'message' => sprintf('门店编号「%s」已经存在，请重新录入',$arg_array['mallCode']));
				}
			}
		}
		
		if(!isset($arg_array['mention']) || !in_array($arg_array['mention'], array(0,1))){
			return array('code'=>400,'message'=>'请选择自提信息');
		}

		if(!isset($arg_array['provinceid']) || !is_numeric($arg_array['provinceid'])){
			return array('code'=>400,'message'=>'省ID号错误');
		}
	
		if(!isset($arg_array['cityid']) || !is_numeric($arg_array['cityid'])){
			return array('code'=>400,'message'=>'市ID错误');
		}
	
		if(!isset($arg_array['countyid']) || !is_numeric($arg_array['countyid'])){
			return array('code'=>400,'message'=>'区ID错误');
		}
	
		
		if(!isset($arg_array['address']) || empty($arg_array['address'])){
			return array('code'=>400,'message'=>'门店地址不能为空');
		}

		//判断省市区是否正确
		$region['id'] = $arg_array['provinceid'];
		$region['level'] = 1;
		$commHandler = new commHandler($this->dbca);
		$province = $commHandler->searchRegion($region);
		
		if($province){
			$pName = $province[0]['name'];
			$region['id'] = $arg_array['cityid'];
			$region['parentID'] = $province[0]['id'];
			$region['level'] = 2;
			$city = $commHandler->searchRegion($region);
			if($city){
				$cName = $city[0]['name'];
				$region['id'] = $arg_array['countyid'];
				$region['parentID'] = $city[0]['id'];
				$region['level'] = 3;
				$county = $commHandler->searchRegion($region);
				if($county){
					$tName = $county[0]['name'];	
				}else{
					return array('code'=>400,'message'=>'县/区区域不存在,请核对');		
				}
			
			
			}else{
				return array('code'=>400,'message'=>'城市区域不存在,请核对');
			}
		
		}else{
			return array('code'=>400,'message'=>'省级区域不存在,请核对');
		}

		try {
			
			//新增或修改门店信息
			$mall_master = new entity('mall_master');
			if (!empty($arg_array['mallID']) && $arg_array['mallID'] > 0) {//修改
				$mall_master->mallID = $arg_array['mallID'];
				if (!$this->dbca->fetch($mall_master)) {
					throw new Exception('门店信息没有找到', 404);
				}
			} else {//增加

				$mall_master->creator = $arg_array['creator'];
			}

			$commHandler = new commHandler($this->dbca);
			$mall_master->mallName     = $commHandler->convertVar( $arg_array['mallName'] );
			$mall_master->mallCode     = $arg_array['mallCode'];
			$mall_master->mention      = $arg_array['mention'];
			$mall_master->description  = $arg_array['description']; 
			$mall_master->mallType     = isset($arg_array['mallType']) ? $arg_array['mallType'] : 0;
			$mall_master->phone        = $arg_array['phone'];
			$mall_master->mobile       = $arg_array['mobile'];
			$mall_master->provinceid   = $arg_array['provinceid'];
			$mall_master->provinceName = $pName;
			$mall_master->cityid       = $arg_array['cityid'];
			$mall_master->cityName     = $cName;
			$mall_master->countyid     = $arg_array['countyid'];
			$mall_master->countyName   = $tName;
			$mall_master->address      = $arg_array['address'];
			if($arg_array['longitude'] != '' && $arg_array['latitude'] != ''){
				$mall_master->longitude    = $arg_array['longitude'];
				$mall_master->latitude     = $arg_array['latitude'];
			}

            if(!$arg_array['mallID']){
			    $mall_master->useFlg       = $arg_array['useFlg'];
            }
			
			//上传图片
			$fileDirHandler = new fileDirHandler();

				if (empty($arg_array['logo_img'])) {
					$oldName = null;
				} else {
					$oldName = G_APPLICATION_BASEPATH . $arg_array['logo_img'];
					$newName = G_IMAGE_SAVE_ROOT . 'mall/' . $fileDirHandler->basename($oldName);
				}
				if (!empty($oldName)) {
					if (!$fileDirHandler->move($oldName, $newName)) {
						throw new Exception('文件移动失败', 404);
					}
				$mall_master->logo = 'mall/' . $fileDirHandler->basename($oldName);
				
				}
				
			$this->dbca->save($mall_master);
			$mallID = $this->dbca->insert_id;
			for($i=0;$i<count($arg_array['det_img']);$i++){
				$fileDirHandler = new fileDirHandler();

				if (empty($arg_array['det_img'][$i])) {
					$oldName = null;
				} else {
					$oldName = G_APPLICATION_BASEPATH . $arg_array['det_img'][$i];
					$newName = G_IMAGE_SAVE_ROOT . 'mall/' . $fileDirHandler->basename($oldName);
				}
				if (!empty($oldName)) {
					if (!$fileDirHandler->move($oldName, $newName)) {
						throw new Exception('文件移动失败', 404);
					}
					$mall_pic = new entity('mall_pic');
					if($mallID){
						$mall_pic->mallID = $mallID;
					}else{
						$mall_pic->mallID = $arg_array['mallID'];
					}
					$mall_pic->sortOrder = $i;
					
					$this->dbca->fetch($mall_pic);
					$mall_pic->creator = $arg_array['creator'];
					$mall_pic->pic = 'mall/' . $fileDirHandler->basename($oldName);
					$this->dbca->save($mall_pic);
				}
			}

            if(!$arg_array['mallID']){
                return array( 'code' => 200, 'message' => '门店保存成功' );
            }else{
                return array( 'code' => 200, 'message' => '门店保存成功','mallID'=> $arg_array['mallID']);
            }



		} catch (Exception $e) {

			if ($e->getCode() > 0) {
				return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
			} else {
				error_log($e->getMessage());
				return array( 'code' => 500, 'message' => '系统错误' );
			}

		}
	
	}
		
	/**
	 * 查询门店的介绍图片
	 */
	public function searchMallPic(&$arg_array) {
		if(!isset($arg_array['mallID']) || $arg_array['mallID'] <0){
			return array('code'=>400,'message'=>'缺少参数');
		}
		$result = $this->dbca->stmt_query('SELECT * FROM mall_pic WHERE mallID=?','i',$arg_array['mallID']);
		if($result){
			foreach($result as &$k){
				$result_array[] = array(
				'mallID'     => $k->mallID,
				'pic'        => $k->pic ? G_IMAGE_URL . $k->pic : G_IMAGE_URL . '/system/comm_default.jpg',
				'picID'      => $k->picID,
				'sortOrder'  => $k->sortOrder
				);
			}
			return $result_array;
		}else{
			return null;		
		}
	}
	
	/**
	 * 删除门店
	 *
	 * @param unknown_type $arg_array
	 */
	public function deleteMall(&$arg_array){
		try{
			$this->dbca->beginTransaction();
			foreach($arg_array as $k){
				//实例化
				$mall_master = new entity('mall_master');
				$mall_master->mallID = $k;
				if($this->dbca->fetch($mall_master)){
					$this->dbca->delete($mall_master,'mall');
				}
			}
			$this->dbca->commit();
			return array( 'code' => 200, 'message' => '删除成功' );

		}catch(Exception $e){
			$this->dbca->rollBack();
			error_log($e->getMessage());
		}		
	}
	
	/**
	 * 门店使用状态修改
	 */
	public function changeMallStatus(&$arg_array){
		//参数检查
		if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '') {
			return array( 'code' => 400, 'message' => '缺少参数' );
		}


		$str_array = explode('_', $arg_array['useFlg_str']);

		try{
			//检查商户是否存在或已经被操作
			$mall_master = new entity('mall_master');
			$mall_master->mallID = $str_array[0] ;
			if (!$this->dbca->fetch( $mall_master )){
				throw new Exception(sprintf('门店号「%d」,的门店不存在,请审核后再操作',$str_array[0]) , 400) ;
			}

			//检查商户状态是否已经被修改
			if($mall_master->useFlg == $str_array[1] && $str_array[1] == 1){
				throw new Exception(sprintf('门店号「%d」,的门店已启用',$str_array[0]) , 400) ;
			}

			if($mall_master->useFlg == $str_array[1] && $str_array[1] == 0){
				throw new Exception(sprintf('门店号「%d」,的门店已禁用',$str_array[0]) , 400) ;
			}

			//保存
			$mall_master->useFlg = $str_array[1] ;
			$this->dbca->save( $mall_master , 'mall_master' );

		}catch (Exception $e) {
			if ($e->getCode() > 0){
				return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
			}else {
				error_log($e->getMessage());
				return array( 'code' => 500, 'message' => '系统错误' );
			}
		}

		if($str_array[1] == 1){
			return array( 'code' => 200, 'message' => '门店启用成功' );
		}else if ($str_array[1] == 0){
			return array( 'code' => 200, 'message' => '门店禁用成功' );
		}
	}

    /**
     * 保存微信前台问卷调查
     */
    function saveQandA( $arg_array ){

        //实例化公共类
        $commHandler = new commHandler();

        if( !isset($arg_array['options'],$arg_array['custName'],$arg_array['mobile'],$arg_array['questionID'],$arg_array['pcustID']) )
            return array( 'code'=>400 , 'message'=>'参数错误' );

        if( !is_numeric($arg_array['mobile']) || !is_numeric($arg_array['questionID']) || !is_numeric($arg_array['pcustID']) )
            return array( 'code'=>400 , 'message'=>'参数错误' );

        if( !is_array($arg_array['options']) || empty($arg_array['options']) )
            return array( 'code'=>400 , 'message'=>'参数错误' );

        if( empty($arg_array['custName']) )
            return array( 'code'=>400 , 'message'=>'真实姓名不能为空' );

        if( empty($arg_array['mobile']) ){
            return array( 'code'=>400 , 'message'=>'联系手机不能为空' );
        }else{

            if( !$commHandler->isMobile($arg_array['mobile']) )
                return array( 'code'=>400 , 'message'=>'联系方式格式有误' );

        }

        //查询门店问卷调查信息
        $mall_questionnaire = new entity('mall_questionnaire');
        $mall_questionnaire->questionID = $arg_array['questionID'];

        if( !$this->dbca->fetch($mall_questionnaire) )
            return array( 'code'=>404 , 'message'=>'没有找到问卷调查信息' );

        //查询用户是否已经参与问卷调查
        $mall_questionnaire_cust = new entity('mall_questionnaire_cust');
        $mall_questionnaire_cust->questionID = $arg_array['questionID'];
        $mall_questionnaire_cust->pcustID = $arg_array['pcustID'];

        if( $this->dbca->fetch($mall_questionnaire_cust) )
            return array( 'code'=>400 , 'message'=>'您已参与该问卷调查' );

        $mall_questionnaire_cust->suggest  = htmlspecialchars($arg_array['suggest']);
        $mall_questionnaire_cust->mobile   = $arg_array['mobile'];
        $mall_questionnaire_cust->custName = $arg_array['custName'];

        try{

            //开启事务
            $this->dbca->beginTransaction();

            //保存问卷调查信息
            $this->dbca->save( $mall_questionnaire_cust );

            //获取刚刚插入的自增量
            $id = $this->dbca->insert_id;

            //问卷调查“调查人数”字段加1
            $mall_questionnaire->questionnaireNum = $mall_questionnaire->questionnaireNum+1;
            $this->dbca->save( $mall_questionnaire );

            //循环保存用户勾选项
            foreach( $arg_array['options'] as $option ){

                //查询投票项信息
                $vote_obj = new entity('mall_questionnaire_vote');
                $vote_obj->questionID = $arg_array['questionID'];
                $vote_obj->voteID = $option['voteID'];

                if( !$this->dbca->fetch($vote_obj) )
                    throw new Exception( '投票项信息有误' , 404 );

                if( $option['optionID'] != 0 ){

                    //查询该选项信息
                    $option_obj = new entity('mall_questionnaire_vote_option');
                    $option_obj->voteID   = $option['voteID'];
                    $option_obj->optionID = $option['optionID'];

                    if( !$this->dbca->fetch($option_obj) )
                        throw new Exception( '选项信息有误' , 404 );

                }

                $cust_vote = new entity('mall_questionnaire_cust_vote');
                $cust_vote->qcID = $id;
                $cust_vote->questionID = $arg_array['questionID'];
                $cust_vote->voteID = $option['voteID'];
                $cust_vote->optionID = $option['optionID'];
                $cust_vote->optionName = $option['optionID'] == 0 ? $option['value'] : $option_obj->optionName;

                //保存投票选项
                $this->dbca->save($cust_vote);

                //该投票项被的“投票数量”加1
                $vote_obj->voteNum = $vote_obj->voteNum+1;
                $this->dbca->save($vote_obj);

                if( $option['optionID'] != 0 ){

                    //该选项被投数量加1
                    $option_obj->optionNum = $option_obj->optionNum+1;
                    $this->dbca->save($option_obj);

                }

            }

            //提交事务
            $this->dbca->commit();

            return array( 'code'=>200 , 'message'=>'保存成功' );

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( $e->getCode() == 404 ){

                return array( 'code'=>500 , 'message'=>$e->getMessage() );

            }else{

                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>'系统错误，操作失败' );

            }

        }

    }

    /**
     * 促销活动审核
     */
    public function promotionVerify(&$arg_array){

        if(!isset($arg_array['promotionID']) || empty($arg_array['promotionID']))
            return(array('code'=>400,'message'=>' 参数传递错误'));

        try {
            $merchant_promotion = new entity('mall_merchant_promotion');
            $merchant_promotion->promotionID = $arg_array['promotionID'];
            if($this->dbca->fetch($merchant_promotion)){
                $merchant_promotion->promotionStatus = 1;
                $this->dbca->save($merchant_promotion);
            }else{
                return(array('code'=>400,'message'=>'不存在该优惠劵'));
            }

            $subscribe_info = $this->dbca->stmt_query('SELECT mmsd.pcustID,mmp.promotionName,mmp.description,mmp.promotionID from mall_merchant_promotion mmp INNER JOIN mall_merchant_subscribe_detail mmsd ON mmp.merchantID = mmsd.merchantID where promotionID = ?','i',$arg_array['promotionID']);

            foreach($subscribe_info as $val){
                $cust_message = new entity('cust_message');
                $cust_message->creator = $arg_array['creator'];
                $cust_message->pcustID = $val->pcustID;
                $cust_message->title = $val->promotionName;
                $cust_message->message = $val->description;
                $cust_message->link = '/weixin/wap/eventSale_detail.html?id='.$subscribe_info[0]->promotionID;
                $this->dbca->save($cust_message);
            }
            return(array('code'=>200,'message'=>'审核成功'));
        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }
	
	/**
     * 使用优惠券
     */
    function useCoupon( $arg_array ){

        //实例化公共类
        $commHandler = new commHandler( $this->dbca );

        if( !isset($arg_array['one'],$arg_array['two'],$arg_array['pwd'],$arg_array['uuid'],$arg_array['useAmount'],$arg_array['couponID']) )
            return array('code'=>400 , 'message'=>'参数错误');

        if( empty($arg_array['one']) || empty($arg_array['two']) || empty($arg_array['pwd']) || empty($arg_array['uuid']))
            return array('code'=>400 , 'message'=>'参数错误');

        if( !$commHandler->isMoney($arg_array['one']) )
            return array('code'=>400 , 'message'=>'首次输入的金额格式有误');

        if( !$commHandler->isMoney($arg_array['two']) )
            return array('code'=>400 , 'message'=>'再次输入的金额格式有误');

        if( $arg_array['one'] != $arg_array['two'] )
            return array('code'=>400 , 'message'=>'两次输入的金额不相等');

        if( !is_numeric($arg_array['pwd']) )
            return array('code'=>400 , 'message'=>'密码必须为整数序列');

        //查询商户（输入的密码为商户ID）
        $search_merchant = 'SELECT * FROM mall_merchant_master WHERE merchantID=?';
        $merchantInfo    = $this->dbca->stmt_query($search_merchant,'i',$arg_array['pwd']);

        if( empty($merchantInfo) )
            return array('code'=>400 , 'message'=>'没有找到商户信息');

        //查询优惠券信息
        $mall_coupon = new entity('mall_coupon');
        $mall_coupon->couponID = $arg_array['couponID'];

        if( !$this->dbca->fetch($mall_coupon) )
            return array('code'=>400 , 'message'=>'没有找到优惠券信息');

        /**
         * 如果该优惠券是商户优惠券，则校验该优惠券是否适用该商户
         */
        if( $mall_coupon->couponType == 2 ){

            //查询该优惠券是否适用该商户
            $is_suit = 'SELECT * FROM mall_coupon_merchant WHERE merchantID=? AND couponID=?';
            $suitInfo    = $this->dbca->stmt_query($is_suit,'ii',array($arg_array['pwd'],$arg_array['couponID']));

            if( empty($suitInfo) )
                return array('code'=>400 , 'message'=>'该优惠券不适用所填商户');

        }

        //查询用户优惠券信息
        $user_coupon = new entity('mall_coupon_code');
        $user_coupon->uuid = $arg_array['uuid'];

        if( !$this->dbca->fetch($user_coupon) )
            return array('code'=>400 , 'message'=>'没有找到信息');

        $user_coupon->useTime       = date('Y-m-d H:i:s');
        $user_coupon->useAmount     = $arg_array['useAmount'];
        $user_coupon->billAmount    = $arg_array['one'];
        $user_coupon->merchantID    = $arg_array['pwd'];
        $user_coupon->merchantName  = $merchantInfo[0]->merchantName;

        try{

            //更新状态
            $this->dbca->save($user_coupon);

            return array('code'=>200 , 'message'=>'使用成功');

        }catch(Exception $e){
            error_log($e->getMessage());
            return array('code'=>500 , 'message'=>'系统错误，操作失败');
        }

    }

    /**
     * 查询用户签到信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
    'sortname' => string 排序字段
    'sortorder' => string 排序方式
    'page' => int 分页页码
    'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchMallCheckIn( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //用户ID
        if ( isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID']) ) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //签到日期
        if ( isset($arg_array['checkInDate']) && !empty($arg_array['checkInDate']) ) {
            $sql .= ' AND checkInDate = ?';
            $params_type .= 's';
            $params_array[] = trim($arg_array['checkInDate']);
        }

        //签到月份
        if ( isset($arg_array['month']) && is_numeric($arg_array['month']) ) {

            //获取今年
            $year = date('Y');

            if( $arg_array['month'] >0 && $arg_array['month'] <10 )
                $month = '0'.$arg_array['month'];
            else
                $month = $arg_array['month'];

            //当月第一天
            $firstDay = $year.'-'.$month.'-01';

            //获取本月最后一天
            $lastDay = date('Y-m-t',strtotime($firstDay));

            $sql .= ' AND checkInDate >= ? && checkInDate <= ?';
            $params_type .= 'ss';
            $params_array[] = $firstDay;
            $params_array[] = $lastDay;
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM mall_check_in ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询用户签到信息
            $search_sql = 'SELECT * FROM mall_check_in ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            $week = array('星期日','星期一','星期二','星期三','星期四','星期五','星期六');

            foreach($temp_item_array as &$item) {

                $a_week = date('w' , strtotime($item->checkInDate));

                $b_week = $week[$a_week];

                $item_array[] = array(
                    'uuid' => $item->uuid,
                    'createTime' => $item->createTime,
                    'pcustID' => $item->pcustID,
                    'checkInDate' => $item->checkInDate,
                    'week' => $b_week,
                    'date' => date('m月d日' , strtotime($item->checkInDate)),
                    'remark'  => $item->remark
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 保存用户签到
     */
    function saveCheckIn( $pcustID , $eai ){

        if( !isset($pcustID) || !is_numeric($pcustID) || empty($pcustID) )
            return array( 'code'=>400 , 'message'=>'签到失败' );

        //查询用户信息
        $custInfo = new entity('cust_master');
        $custInfo->pcustID = $pcustID;

        if( !$this->dbca->fetch($custInfo) )
            return array( 'code'=>400 , 'message'=>'用户信息有误' );

        $checkIn_obj = new entity('mall_check_in');
        $checkIn_obj->pcustID = $pcustID;
        $checkIn_obj->checkInDate = date('Y-m-d');

        if( $this->dbca->fetch($checkIn_obj) )
            return array( 'code'=>400 , 'message'=>'您今日已经签到' );

        $checkIn_obj->creator = $pcustID;

        quanli_include('module/base/promotionHandler.class.php');    //加载促销活动类

        $promotionHandler = new promotionHandler( $this->dbca );  //实例化促销类

        $promotionData = $promotionHandler->grantCustPromotion( $pcustID, $custInfo->custID, 3, $eai ); //查询会员促销活动

        if( $promotionData['code'] == 200 ){
            $checkIn_obj->remark = $promotionData['data']['points'];
        }else{
            $checkIn_obj->remark = 0;
        }

        try{

            //保存签到
            $this->dbca->save($checkIn_obj);

            return array( 'code'=>200 , 'message'=>'签到成功', 'data' => array( 'points' => $checkIn_obj->remark ) );

        }catch (Exception $e){
            error_log($e->getMessage());
            return array( 'code' => 500, 'message' => '系统错误,签到失败' );
        }

    }

    /**
     *  保存客户建议
     * @param $arg_array
     * $arg_array = array(
     *          custName => 客户名
     *          content => 建议内容
     *          mobile => 手机号码
     *          pcustID => 会员号
     * )
     * @return array|null
     */
    public function saveCustMessage(&$arg_array){

        if(!isset($arg_array['pcustID']) || empty($arg_array['pcustID']))
            return array('code'=>400,'message'=>'参数错误');

        $commHandler = new commHandler($this->dbca);

        if(!isset($arg_array['custName']) || empty($arg_array['custName']))
            return array('code'=>400,'message'=>'姓名不能为空');

        if(!isset($arg_array['content']) || empty($arg_array['content']))
            return array('code'=>400,'message'=>'建议内容不能为空');

        if(!isset($arg_array['mobile']) || empty($arg_array['mobile']))
            return array('code'=>400,'message'=>'手机号码不能为空');

        if(!$commHandler->isMobile($_REQUEST['mobile']))
            return array('code'=>400,'message'=>'手机号码格式不正确');

        try{

            $cust_master = $this->dbca->stmt_query('SELECT custID FROM cust_master WHERE pcustID = ? ','i',$arg_array['pcustID']);

            $custID = $cust_master[0]->custID;

            $content_suggest = new entity('content_suggest');

            $content_suggest->pcustID = $arg_array['pcustID'];
            $content_suggest->custID = $custID;
            $content_suggest->content = $arg_array['content'];
            $content_suggest->custName = $arg_array['custName'];
            $content_suggest->mobile = $arg_array['mobile'];
            $content_suggest->suggestStatus = 0;

            $this->dbca->save($content_suggest);

            return array('code'=>200,'message'=>'保存成功');

        }catch (Exception $e){
            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 获取经纬度之间的距离
     * @param $lng1
     * @param $lat1
     * @param $lng2
     * @param $lat2
     * @return int
     */
    public function getdistance($lngLatOne,$lngLatTwo){

        $lng1 = $lngLatOne[0];
        $lat1 = $lngLatOne[1];
        $lng2 = $lngLatTwo[0];
        $lat2 = $lngLatTwo[1];
        //将角度转为狐度
        $radLat1=deg2rad($lat1);//deg2rad()函数将角度转换为弧度
        $radLat2=deg2rad($lat2);
        $radLng1=deg2rad($lng1);
        $radLng2=deg2rad($lng2);
        $a=$radLat1-$radLat2;
        $b=$radLng1-$radLng2;
        $s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137*1000;

        return sprintf("%.2f", $s/1000);
    }
    
    /**
     * 修改自提信息
     *
     */
    public function changeMention(&$arg_array){
    	//参数检查
		if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '') {
			return array( 'code' => 400, 'message' => '缺少参数' );
		}

		$str_array = explode('_', $arg_array['useFlg_str']);

		try{
			//检查商户是否存在或已经被操作
			$mall_master = new entity('mall_master');
			$mall_master->mallID = $str_array[0] ;
			if (!$this->dbca->fetch( $mall_master )){
				throw new Exception(sprintf('门店号「%d」,的门店不存在,请审核后再操作',$str_array[0]) , 400) ;
			}

			//保存
			$mall_master->mention = $str_array[1] ;
			$this->dbca->save( $mall_master , 'mall_master' );

		}catch (Exception $e) {
			if ($e->getCode() > 0){
				return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
			}else {
				error_log($e->getMessage());
				return array( 'code' => 500, 'message' => '系统错误' );
			}
		}

		if($str_array[1] == 1){
			return array( 'code' => 200, 'message' => '门店自提状态更新成功' );
		}else if ($str_array[1] == 0){
			return array( 'code' => 200, 'message' => '门店自提状态更新成功' );
		}
    }

}